Idioms: Part 2

Continue studying some of the commonly used Perl idioms.

Handling the main code

Many programs commonly set up several file-scoped lexical variables before handing off processing to other functions. It’s tempting to use these variables directly, rather than passing values to and returning values from functions, especially as programs grow. Unfortunately, these programs may come to rely
on subtleties of what happens during Perl’s compilation process—a variable we thought would be initialized to a specific value may not get initialized until much later. Remember that Perl requires no special syntax for creating closures—we can close over a lexical variable inadvertently.

To avoid this, wrap the main code of your program in a single function, main(). Encapsulate the variables to their proper scopes. Then, add a single line to the beginning of your program, after you’ve used all the modules and pragmas you need:

Get hands-on with 1200+ tech skills courses.