Compile-time Manipulation

Learn how to do compile-time manipulation during code generation.

Unlike code written explicitly as code, code generated through string eval gets compiled while our program is running. Where we might expect a normal function to be available throughout the lifetime of our program, a generated function might not be available when we expect it.

The BEGIN block

Force Perl to run code—to generate other code—during compilation by wrapping it in a BEGIN block. When the Perl parser encounters a block labeled BEGIN, it parses and compiles the entire block and then runs it (unless it has syntax errors). When the block finishes running, parsing will continue as if there was no interruption. The difference between writing these two codes is primarily one of maintainability. We could argue for and against either.

Access this course and 1400+ top-rated courses and projects.