Search⌘ K

Global Variables

Explore the use and management of Perl's super global variables that affect program behavior globally. Learn techniques like localizing globals, using English names for clarity, and alternatives such as Try::Tiny and lexical filehandles to minimize side effects. This lesson helps you write safer and more maintainable Perl code by understanding common globals and their proper usage.

Overview

Perl provides several super global variables. They’re not scoped to a package or file. They’re really, truly global. Unfortunately, any direct or indirect modifications of these variables may change the behavior of other parts of the program. Experienced Perl hackers have memorized some of them. Few people have memorized all of them—they’re terse. Only a handful are regularly useful. perldoc perlvar contains the exhaustive list of these variables.

Managing super globals

As Perl evolves, it moves more global behavior into lexical behavior, so that we can avoid many of these globals. When we must use them, we use local in the smallest possible scope to constrain any modifications. We're still susceptible to any changes made to these variables from code we call, but we reduce the likelihood of surprising code outside our scope. As the easy file-slurping idiom demonstrates, local is often the right approach:

Perl
my $file; { local $/; $file = <$fh> };

The effect of localizing $/ lasts only through the end of the block. There’s a low chance that any Perl code will run as a result of reading lines from the filehandle and change the value of $/ within the do block.

Not all cases of using super globals are this easy to guard, but this often works.

Other times we need to read the value of a super global and hope that no other code ...