Skip to content

Latest commit

 

History

History
241 lines (177 loc) · 8.04 KB

globals.pod

File metadata and controls

241 lines (177 loc) · 8.04 KB

Global Variables

Perl 5 provides several super global variables that are truly global, not scoped to a package or file. Unfortunately, their global availability means that any direct or indirect modifications may have effects on other parts of the program--and they're terse. Experienced Perl 5 programmers have memorized some of them. Few people have memorized all of them. Only a handful are ever useful. perldoc perlvar contains the exhaustive list of such variables.

Managing Super Globals

Perl 5 continues to move more global behavior into lexical behavior, so you can avoid many of these globals. When you can't avoid them, use local in the smallest possible scope to constrain any modifications. You are still susceptible to any changes code you call makes to those globals, but you reduce the likelihood of surprising code outside of your scope. As the easy file slurping idiom (easy_file_slurping) demonstrates, local is often the right approach:

The effect of localizing $/ lasts only through the end of the block. There is a low chance that any Perl code will run as a result of reading lines from the filehandleA tied filehandle (tie) is one of the few possibilities. 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 you need to read the value of a super global and hope that no other code has modified it. Catching exceptions with an eval block can be susceptible to race conditions, in that DESTROY() methods invoked on lexicals that have gone out of scope may reset $@:

Copy $@ immediately after catching an exception to preserve its contents. See also Try::Tiny instead (exception_caveats).

English Names

The core English module provides verbose names for punctuation-heavy super globals. Import them into a namespace with:

This allows you to use the verbose names documented in perldoc perlvar within the scope of this pragma.

Three regex-related super globals ($&, $`, and $') impose a global performance penalty for all regular expressions within a program. If you forget the -no_match_vars import, your program will suffer the penalty even if you don't explicitly read from those variables.

Modern Perl programs should use the @- variable as a replacement for the terrible three.

I don't understand this strategy. What is being replaced? In Modern Perl, we have the /p modifier with gives us the not-so-terrible three, ${^MATCH}, ${^PREMATCH}, and ${^POSTMATCH}.

Useful Super Globals

Most modern Perl 5 programs can get by with using only a couple of the super globals. You're most likely to encounter only a few of these variables in real programs.

  • $/ (or $INPUT_RECORD_SEPARATOR from the English pragma) is a string of zero or more characters which denotes the end of a record when reading input a line at a time. By default, this is your platform-specific newline character sequence. If you undefine this value, Perl will attempt to read the entire file into memory. If you set this value to a reference to an integer, Perl will try to read that many bytes per record (so beware of Unicode concerns). If you set this value to an empty string (''), Perl will read in a paragraph at a time, where a paragraph is a chunk of text followed by an arbitrary number of newlines.

  • $. ($INPUT_LINE_NUMBER) contains the number of records read from the most recently-accessed filehandle. You can read from this variable, but writing to it has no effect. Localizing this variable will localize the filehandle to which it refers.

  • $| ($OUTPUT_AUTOFLUSH) governs whether Perl will flush everything written to the currently selected filehandle immediately or only when Perl's buffer is full. Unbuffered output is useful when writing to a pipe or socket or terminal which should not block waiting for input. This variable will coerce any values assigned to it to boolean values.

  • @ARGV contains the command-line arguments passed to the program.

  • $! ($ERRNO) is a dualvar (dualvars) which contains the result of the most recent system call. In numeric context, this corresponds to C's errno value, where anything other than zero indicates an error. In string context, this evaluates to the appropriate system error string. Localize this variable before making a system call (implicitly or explicitly) to avoid overwriting the appropriate value for other code elsewhere. Many places within Perl 5 itself make system calls without your knowledge, so the value of this variable can change out from under you. Copy it immediately after causing a system call for the most accurate results.

  • $" ($LIST_SEPARATOR) is a string used to separate array and list elements interpolated into a string.

  • %+ contains named captures from successful regular expression matches (named_captures).

  • $@ ($EVAL_ERROR) contains the value thrown from the most recent exception (catching_exceptions).

  • $0 ($PROGRAM_NAME) contains the name of the program currently executing. You may modify this value on some Unix-like platforms to change the name of the program as it appears to other programs on the system, such as ps or top.

  • $$ ($PID) contains the process id of the currently running instance of the program, as the operating system understands it. This will vary between fork()ed programs and may vary between threads in the same program.

  • @INC holds a list of filesystem paths in which Perl will look for files to load with use or require. See perldoc -f require for other items this array can contain.

  • %SIG maps OS and low-level Perl signals to function references used to handle those signals. Trap the standard Ctrl-C interrupt by catching the INT signal, for example. See perldoc perlipc for more information about signals and especially safe signals.

Alternatives to Super Globals

The worst culprits for action at a distance relate to IO and exceptional conditions. Using Try::Tiny (exception_caveats) will help insulate you from the tricky semantics of proper exception handling. localizing and copying the value of $! can help you avoid strange behaviors when Perl makes implicit system calls. Using IO::File and its methods on lexical filehandles (file_handling_variables) helps prevent unwanted global changes to IO behavior.

POD ERRORS

Hey! The above document had some coding errors, which are explained below:

Around line 3:

A non-empty Z<>

Around line 35:

Deleting unknown formatting code N<>

Around line 102:

=end for without matching =begin. (Stack: [empty])