Skip to content

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.

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 perl
use strict;
use warnings;
my @words = ('hickory', 'dickory', 'doc');
# Example 1: foreach loop
foreach 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 default

Common uses of $_ as default:

  • Iterator variable in foreach loops 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 in while loop conditions like while (<FH>).
  • Implicit iterator variable in grep and map.

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 perl
use 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";

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)

These are scalar variables with global scope and special meaning.

VariableEnglish Name (use English;)Description
$_$ARGThe default input and pattern-searching space.
$.$NRCurrent input line number of the last filehandle read. Resets on explicit close.
$/$RSInput record separator (newline \n by default). Setting to undef reads the whole file; "" treats blank lines as separators.
$,$OFSOutput field separator for the print operator when printing a list.
$\$ORSOutput record separator, appended after each print.
$"$LIST_SEPARATORSeparator used when interpolating an array into a double-quoted string. Default is a space.
$;$SUBSCRIPT_SEPARATORSubscript separator for multidimensional array emulation (rarely used directly). Default is \034 (ASCII FS).
$^L$FORMAT_FORMFEEDWhat a format outputs to perform a formfeed. Default is \f.
$: $FORMAT_LINE_BREAK_CHARACTERSSet of characters after which a string may be broken for format continuation fields. Default is "\n"-".
$^A$ACCUMULATORThe current value of the write accumulator for format lines.
$?$CHILD_ERRORStatus returned by the last pipe close, backtick (“) command, system() call, or waitpid().
$!$OS_ERROR or $ERRNOIn numeric context, the current errno value. In string context, the corresponding system error message.
$@$EVAL_ERRORPerl syntax error message from the last eval BLOCK or do FILE or require that failed.
$$$PROCESS_ID or $PIDThe process ID (PID) of the Perl script currently executing.
$<$REAL_USER_ID or $UIDThe real user ID (UID) of this process.
$>$EFFECTIVE_USER_ID or $EUIDThe effective user ID (EUID) of this process.
$($REAL_GROUP_ID or $GIDThe real group ID (GID) of this process (or list of gids if use POSIX 'getgroups';).
$)$EFFECTIVE_GROUP_ID or $EGIDThe effective group ID (EGID) of this process (or list of gids).
$0$PROGRAM_NAMEThe name of the file containing the Perl script being executed.
$]$PERL_VERSIONThe version of Perl interpreter (e.g., 5.032001 for v5.32.1).
$^D$DEBUGGINGCurrent value of the debugging flags (set with -D command-line option).
$^E$EXTENDED_OS_ERRORExtended error information on some operating systems (e.g., Win32 error codes).
$^F$SYSTEM_FD_MAXMaximum system file descriptor, usually 2. Higher values may be OS-dependent.
$^HContains internal compiler hints enabled by certain pragmatic modules. Not for general use.
$^I$INPLACE_EDITIn-place-edit extension. Used with <> and -i switch. undef to disable.
$^MEmergency memory pool. Requires a special Perl build. Rarely used.
$^O$OSNAMEOperating system name Perl was built for (e.g., ‘linux’, ‘darwin’, ‘MSWin32’).
$^P$PERLDBInternal flag for the debugger.
$^T$BASETIMEScript start time, in seconds since the epoch.
$^W$WARNINGCurrent value of the warning switch (true if warnings are enabled via -w or use warnings).
$^X$EXECUTABLE_NAMEThe name that the Perl binary itself was executed as.
VariableEnglish NameDescription
@ARGVContains the command-line arguments passed to the script.
@INCList of directories where do, require, and use look for Perl modules and libraries.
@FArray 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.
VariableEnglish NameDescription
%INCContains entries for each filename included via do, require, or use. Keys are filenames, values are path to file.
%ENVContains the current environment variables.
%SIGUsed to set signal handlers for various signals (e.g., $SIG{INT} = sub { ... };).
FilehandleEnglish NameDescription
ARGVSpecial filehandle that iterates over command-line filenames in @ARGV. Used by the null filehandle operator <>.
STDINStandard input filehandle.
STDOUTStandard output filehandle.
STDERRStandard error filehandle.
DATARefers 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.
ConstantEnglish NameDescription
__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.

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.

VariableEnglish NameDescription
$1, $2, ...Contain the text matched by the Nth capture group (parentheses) in the last successful match.
$&$MATCHThe string matched by the last successful pattern.
$` $PREMATCHThe string preceding whatever was matched by the last successful pattern.
$'$POSTMATCHThe string following whatever was matched by the last successful pattern.
$+$LAST_PAREN_MATCHThe 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.

VariableEnglish NameDescription
$|$OUTPUT_AUTOFLUSHIf set to non-zero, forces a flush after every write or print on the currently selected output channel. Default is 0 (false).
$%$FORMAT_PAGE_NUMBERCurrent page number of the selected output channel for formats.
$=$FORMAT_LINES_PER_PAGECurrent page length (printable lines) for formats. Default is 60.
$-$FORMAT_LINES_LEFTNumber of lines left on the page for formats.
$~$FORMAT_NAMEName of the current report format for the selected output channel.
$^$FORMAT_TOP_NAMEName of the current top-of-page format for the selected output channel.

$[: 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.