O'Reilly logo

Perl Best Practices by Damian Conway

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 5. Variables

Variables won't. Constants aren't.

Osborn's Law

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required