Chapter 7. The Perl Compiler

7.1. What is the Perl Compiler?

In 1996, someone announced a challenge - the first person to write a compiler suite for Perl would win a laptop. Malcolm Beattie stepped up to the challenge, and won the laptop with his B suite of modules. Many of these modules have now been brought into the Perl core as standard modules.

The Perl compiler is not just for compiling Perl code to a standalone executable - in fact, some would argue that it's not at all for compiling Perl into a standalone executable. We've already seen the use of the B::Terse and B::Tree modules to help us visualise the Perl op tree, and this should give us a hint as to what the Perl compiler is actually all about.

The compiler comes in three parts: a frontend module, O, which does little other than turn on Perl's -c (compile only, do not run) flag, and loads up a backend module, such as B::Terse which performs a specific compiler task, and the B module which acts as a low-level driver.

The B, at the heart of the compiler, is a stunningly simple XS module which makes Perl's internal object-like structures - SVs, ops, and so on - into real Perl-space objects. This provides us with a degree of introspection: we can, for instance, write a backend module which traverses the op tree of a compiled program and dump out its state to a file. (This is exactly what the B::Bytecode module does.)

It's important to know what the Perl compiler is not. It's not something which will magically make your code go faster, or take up less space, or be more reliable. The backends which generate standalone code generally do exactly the opposite. All the compiler is, essentially, is a way of getting access to the op tree and doing something potentially interesting with it. Let's now take a look at some of the interesting things that can be done with it.