Perl Special Variables
Perl - Special Variables
Section titled “Perl - Special Variables”Perl has a number of predefined special variables that have specific meanings and behaviours. These variables often use punctuation characters (e.g., $_, $!, @_) or have longer, more descriptive English-like names available via the use English; pragma.
Understanding these variables is key to writing idiomatic and effective Perl code. Some are read-only, while others can be modified to change Perl’s behavior.
The Default Variable: $_ ($ARG)
Section titled “The Default Variable: $_ ($ARG)”Perhaps the most famous special variable is $_. It serves as a default argument or target for many functions and operations if no explicit one is provided.
#!/usr/bin/env perluse strict;use warnings;
my @words = ('hickory', 'dickory', 'doc');
# Example 1: foreach loopforeach my $word (@words) { # $word is explicitly used print "Word: $word\n";}
print "---\n";
# foreach loop implicitly uses $_foreach (@words) { print "Implicitly: $_\n"; chomp; # chomp acts on $_ by default s/i/I/g; # substitution acts on $_ by default print "Modified: $_\n";}
print "---\n";
# Example 2: Reading from STDIN# print "Enter some text: ";# while (<STDIN>) { # <STDIN> reads a line into $_# print "You entered: $_" if defined $_;# }# (Commented out for non-interactive execution)
$_ = "Test string for functions\n";print; # prints $_ by default
print "Length of '$_': ", length, "\n"; # length operates on $_ by defaultCommon uses of $_ as default:
- Iterator variable in
foreachloops if no explicit variable is given. - Argument to many unary functions (e.g.,
print,chomp,chop,lc,uc,length,defined, file tests like-f). - Target for pattern matching (
m//), substitution (s///), and transliteration (tr///) when no=~operator is used. - The variable where line input operators (e.g.,
<FILEHANDLE>) store the line, especially inwhileloop conditions likewhile (<FH>). - Implicit iterator variable in
grepandmap.
use English; for Long Names
Section titled “use English; for Long Names”To improve readability, you can use the English pragma, which provides longer, more descriptive aliases for many cryptic special variables. For example, $! becomes $OS_ERROR.
#!/usr/bin/env perluse strict;use warnings;use English qw( -no_match_vars ); # -no_match_vars avoids performance hit of $`, $&, $'
open my $fh, '<', 'non_existent_file.txt' or die "Cannot open file: $OS_ERROR\n"; # $OS_ERROR is alias for $!
# $PID is alias for $$print "Current Process ID: $PID\n";Categories of Special Variables
Section titled “Categories of Special Variables”Special variables can be broadly categorized:
- Global Scalar Special Variables
- Global Array Special Variables
- Global Hash Special Variables
- Global Special Filehandles
- Global Special Constants
- Regular Expression Special Variables
- Filehandle-Specific Special Variables (often related to Formats)
Global Scalar Special Variables
Section titled “Global Scalar Special Variables”These are scalar variables with global scope and special meaning.
| Variable | English Name (use English;) | Description |
|---|---|---|
$_ | $ARG | The default input and pattern-searching space. |
$. | $NR | Current input line number of the last filehandle read. Resets on explicit close. |
$/ | $RS | Input record separator (newline \n by default). Setting to undef reads the whole file; "" treats blank lines as separators. |
$, | $OFS | Output field separator for the print operator when printing a list. |
$\ | $ORS | Output record separator, appended after each print. |
$" | $LIST_SEPARATOR | Separator used when interpolating an array into a double-quoted string. Default is a space. |
$; | $SUBSCRIPT_SEPARATOR | Subscript separator for multidimensional array emulation (rarely used directly). Default is \034 (ASCII FS). |
$^L | $FORMAT_FORMFEED | What a format outputs to perform a formfeed. Default is \f. |
$: | $FORMAT_LINE_BREAK_CHARACTERS | Set of characters after which a string may be broken for format continuation fields. Default is "\n"-". |
$^A | $ACCUMULATOR | The current value of the write accumulator for format lines. |
$? | $CHILD_ERROR | Status returned by the last pipe close, backtick (“) command, system() call, or waitpid(). |
$! | $OS_ERROR or $ERRNO | In numeric context, the current errno value. In string context, the corresponding system error message. |
$@ | $EVAL_ERROR | Perl syntax error message from the last eval BLOCK or do FILE or require that failed. |
$$ | $PROCESS_ID or $PID | The process ID (PID) of the Perl script currently executing. |
$< | $REAL_USER_ID or $UID | The real user ID (UID) of this process. |
$> | $EFFECTIVE_USER_ID or $EUID | The effective user ID (EUID) of this process. |
$( | $REAL_GROUP_ID or $GID | The real group ID (GID) of this process (or list of gids if use POSIX 'getgroups';). |
$) | $EFFECTIVE_GROUP_ID or $EGID | The effective group ID (EGID) of this process (or list of gids). |
$0 | $PROGRAM_NAME | The name of the file containing the Perl script being executed. |
$] | $PERL_VERSION | The version of Perl interpreter (e.g., 5.032001 for v5.32.1). |
$^D | $DEBUGGING | Current value of the debugging flags (set with -D command-line option). |
$^E | $EXTENDED_OS_ERROR | Extended error information on some operating systems (e.g., Win32 error codes). |
$^F | $SYSTEM_FD_MAX | Maximum system file descriptor, usually 2. Higher values may be OS-dependent. |
$^H | Contains internal compiler hints enabled by certain pragmatic modules. Not for general use. | |
$^I | $INPLACE_EDIT | In-place-edit extension. Used with <> and -i switch. undef to disable. |
$^M | Emergency memory pool. Requires a special Perl build. Rarely used. | |
$^O | $OSNAME | Operating system name Perl was built for (e.g., ‘linux’, ‘darwin’, ‘MSWin32’). |
$^P | $PERLDB | Internal flag for the debugger. |
$^T | $BASETIME | Script start time, in seconds since the epoch. |
$^W | $WARNING | Current value of the warning switch (true if warnings are enabled via -w or use warnings). |
$^X | $EXECUTABLE_NAME | The name that the Perl binary itself was executed as. |
Global Array Special Variables
Section titled “Global Array Special Variables”| Variable | English Name | Description |
|---|---|---|
@ARGV | Contains the command-line arguments passed to the script. | |
@INC | List of directories where do, require, and use look for Perl modules and libraries. | |
@F | Array into which input lines are split when the -a command-line switch is used (autosplit mode). | |
@_ | Within a subroutine, contains the arguments passed to that subroutine. |
Global Hash Special Variables
Section titled “Global Hash Special Variables”| Variable | English Name | Description |
|---|---|---|
%INC | Contains entries for each filename included via do, require, or use. Keys are filenames, values are path to file. | |
%ENV | Contains the current environment variables. | |
%SIG | Used to set signal handlers for various signals (e.g., $SIG{INT} = sub { ... };). |
Global Special Filehandles
Section titled “Global Special Filehandles”| Filehandle | English Name | Description |
|---|---|---|
ARGV | Special filehandle that iterates over command-line filenames in @ARGV. Used by the null filehandle operator <>. | |
STDIN | Standard input filehandle. | |
STDOUT | Standard output filehandle. | |
STDERR | Standard error filehandle. | |
DATA | Refers to data after the __END__ (or __DATA__ in a required file) token. | |
_ (underscore) | Special filehandle used to cache information from the last stat, lstat, or file test operator. |
Global Special Constants
Section titled “Global Special Constants”| Constant | English Name | Description |
|---|---|---|
__END__ | Indicates the logical end of your script. Text after __END__ can be read via the DATA filehandle. | |
__DATA__ | Similar to __END__, but used in modules or files loaded by require or do. The DATA filehandle for a __DATA__ section is local to the package where __DATA__ was found. | |
__FILE__ | The filename of the current file at compile time. | |
__LINE__ | The current line number in the script at compile time. | |
__PACKAGE__ | The current package name at compile time. |
Regular Expression Special Variables
Section titled “Regular Expression Special Variables”These are set after a successful regular expression match.
Note: Using $, $&, or $' can slow down all regex matches in your program. Modern Perl often encourages using @- and @+ (match start/end positions) or named captures (%+, %-) with the /p flag or use re 'strict'; for better performance and clarity.
| Variable | English Name | Description |
|---|---|---|
$1, $2, ... | Contain the text matched by the Nth capture group (parentheses) in the last successful match. | |
$& | $MATCH | The string matched by the last successful pattern. |
$` | $PREMATCH | The string preceding whatever was matched by the last successful pattern. |
$' | $POSTMATCH | The string following whatever was matched by the last successful pattern. |
$+ | $LAST_PAREN_MATCH | The text matched by the highest-numbered capture group in the last successful match. |
@- | Array: @-[0] is the offset of the start of the last successful match. @-[N] is the offset of the start of the Nth capture group. | |
@+ | Array: @+[0] is the offset of the end of the last successful match. @+[N] is the offset of the end of the Nth capture group. | |
%+ | Hash: Contains named captures from the last successful match (if using (?<name>...)). Keys are capture names, values are matched strings. | |
%- | Hash: Like %+, but values are arrays of all captures for a given name (useful if a named capture group matches multiple times). |
Filehandle-Specific Special Variables (often for Formats)
Section titled “Filehandle-Specific Special Variables (often for Formats)”These variables usually affect the currently selected output filehandle (see select()). Many are related to Perl’s format feature, which is rarely used in modern Perl.
| Variable | English Name | Description |
|---|---|---|
$| | $OUTPUT_AUTOFLUSH | If set to non-zero, forces a flush after every write or print on the currently selected output channel. Default is 0 (false). |
$% | $FORMAT_PAGE_NUMBER | Current page number of the selected output channel for formats. |
$= | $FORMAT_LINES_PER_PAGE | Current page length (printable lines) for formats. Default is 60. |
$- | $FORMAT_LINES_LEFT | Number of lines left on the page for formats. |
$~ | $FORMAT_NAME | Name of the current report format for the selected output channel. |
$^ | $FORMAT_TOP_NAME | Name of the current top-of-page format for the selected output channel. |
Deprecated Special Variables
Section titled “Deprecated Special Variables”$[: This variable, which set the first index of arrays, has been removed from Perl since version 5.30. Array indices always start at 0.
$#: While $#array_name still gives the last index of @array_name, the use of $# alone for setting a default output format for numbers is deprecated and has no effect in modern Perl.