Chapter 5. Variables
Variables won't. Constants aren't.
Compared to most mainstream languages, Perl has an embarrassingly rich variety of built-in variables. The largest group of these are the global punctuation variables—$_, $/, $|, @_, @+, %!, %^H
—which control a wide range of fundamental program behaviours, and which are largely responsible for Perl's unwarranted reputation as "executable line-noise". Other standard variables have more obvious names—@ARGV, %SIG, ${^TAINT}
—but are still global in their scope, and in their effects as well.
Perl also provides self-declaring package variables. These will silently spring into existence the first time they're referred to, helpfully converting typos into valid, but incorrect, code.
This chapter presents a series of coding practices that can minimize the problems associated with Perl's sometimes over-helpful built-in variables. It also offers some techniques for making the most efficient use of variables you create yourself.
Lexical Variables
Avoid using non-lexical variables.
Stick to using only lexical variables (my
), unless you genuinely need the functionality that only a package or punctuation variable can provide.
Using non-lexical variables increases the "coupling" of your code. If two otherwise unrelated sections of code both use a package variable, those two pieces of code can interact with each other in very subtle ways, just by the way they each interact with that shared variable. In other words, without full knowledge ...
Get Perl Best Practices now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.