Perl is a wonderful language. We, along with at least a million other programmers, love it dearly. It?s great for all kinds of applications: text processing, network programming, system administration, and much more. But there are times when we need to go beyond the core of the language and do something not provided by Perl.
Sometimes we do this without noticing it: several modules that ship with Perl call out to C routines to get their work done, as do some of the most commonly used CPAN modules. Other times, we do it deliberately: the various modules for building graphical applications in Perl almost all, directly or indirectly, use external C libraries. Either way, writing extensions to Perl has historically been a bit of a black art. We don?t believe this situation is fair, so we?ve written this book to attempt to demystify the process of relating Perl and C.
That?s not to say we?re fed up with writing modules in Perl. Both of us write many of our modules in Perl, and although sometimes it might be easier to interface to C, we?ve decided to stick with Perl. In fact, writing a module in Perl has a number of advantages over using other languages:
People program in Perl for a reason, and this fact should not be forgotten when it comes to deciding whether to use Perl for an extension module. These issues were addressed in the development of the standard File::Temp module (part of Perl 5.6.1). This module provides a standard interface for creating temporary files from Perl. The original intention was that this module would be written in C, but it quickly became apparent that a Perl implementation would be easier because of portability problems (it was to be a standard module, so it would have to work on all platforms supported by Perl); in addition, speed would not be an issue unless thousands of temporary files were required.
Having addressed why not to use a language other than Perl, we must now present two important reasons why another language is sometimes required:
As well as extending Perl by writing modules in C, sometimes it?s advantageous to go the other way around: to add the flexibility of a Perl interpreter to an existing C program. Like extending, this process has a fearsome reputation, and so we provide two chapters on the topic. Chapter 8 introduces embedding Perl, and chapter 9 includes a full working example that explains Perl embedding.
We also realize that people want to know what?s really going on under the hood, so we conclude our study of the interaction between C and Perl by examining the C sources of the perl interpreter itself, together with details of how to get involved in becoming a developer maintaining perl. Finally, we look ahead to Perl 6 and the Parrot project.