CHAPTER 8
Programming Perl in C
T
HE NEXT THREE CHAPTERS
teach a black art programming Perl modules in C. To
get the most out of these chapters you'll need to have some experience with the C
programming language. You don't need to be a C guru, but you do need to know
your pointers and macros. If you're worried that you don't know enough C, I
suggest you buy a good C reference and give it a try. When you get stuck, hit the
books I think you'll find it happening less often than you expect.
This chapter presents an introduction to Perl's C API. Next, the XS system is pre
sented in Chapter 9. XS is the system used by the vast majority of C modules on CPAN
today. Finally, in Chapter 10, I'll show you a shortcut Inline::C. Inline::C is a brand
new module that I predict will be used for the majority C modules in the future.
One thing this chapter won't do is explain how Perl works. This is fascinating
material but largely unrelated to the task of writing Perl modules in C. For pointers
to documentation on this and other related topics, see the References section at
the end of the chapter.
Why C?
Writing Perl modules in C is a lot more work than writing them in Perl. The end
result is likely to be buggier and less portable than an equivalent implementation
in Perl. As such, you should be hesitant to write in C unless you have a good reason.
So, what constitutes a good reason? The best reason is simple: because you
have to. There are times when Perl simply cannot do what you need done. For
example, when you need to interface with a library written in C, you have no choice
but to write some C code. CPAN contains numerous examples of this type of
module Tk, GD, most of the DBD drivers, and many more. When you come
across a C library that provides a new service, you should consider it a great oppor
tunity to create a new CPAN module.
A common, often misguided, reason to create Perl modules in C is to increase
performance. The reasoning is misguided because the Perl interpreter itself is
written in C. Thus most of what a Perl program does is already happening in highly
optimized C code. You have to believe you can do better than the C gurus that
created Perl to think that your module will be faster simply by being written in C.
1
1. Mark Jason Dominus's article Why Not Translate Perl to C? on Perl.com contains an
extended proof of this assertion. You can find the article at http://www.perl.com/pub/a/2001/
06/27/ctoperl.html.
175
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved