Perl Special Variables

The Perl language defines some special variables, usually prefixed with $, @, or %, for example: $_.

Many special variables have a long English name; the OS error variable $! can be written as $OS_ERROR.

If you want to use special variables with English names, you need to add the following at the top of the program:use English;This allows you to use descriptive English special variable names.

The most commonly used special variable is $_, which contains the default input and pattern matching content. Example:

Example

#!/usr/bin/perl foreach ('Google','Example','Taobao') { print $_; print "\n"; }

Running the above program produces the output:

Google
Example
Taobao

In the following example, we do not use $_ to output content:

Example

#!/usr/bin/perl foreach ('Google','Example','Taobao') { print; print "\n"; }

Running the above program produces the output:

Google
Example
Taobao

In the example, it first outputs "Google", then outputs "Example", and finally outputs "Taobao".

In an iteration loop, the current loop's string is placed in $_, then output via print. Additionally, print uses $_ by default when no output variable is specified.

The following are places where Perl assumes $_ is used even if it is not explicitly written:

  • Various unary functions, including functions like ord() and int(), as well as all file test operators ("-f", "-d") except "-t"; "-t" operates on STDIN by default.
  • Various list functions, such as print() and unlink().
  • Pattern matching operations "m//", "s///", and "tr///" when the "=~" operator is not used.
  • The default iteration variable for a "foreach" loop when no other variable is given.
  • The implicit iteration variable for the grep() and map() functions.
  • When "while" has only a single condition and that condition tests the result of a "<>" operation, $_ is the default location for storing the input record. This only happens in a "while" test condition. (Mnemonic: the underscore can be omitted in certain operations.)

Special Variable Types

According to the usage characteristics of special variables, they can be divided into the following categories:

  • Global scalar special variables.

  • Global array special variables.

  • Global hash special variables.

  • Global special file handles.

  • Global special constants.

  • Regular expression special variables.

  • File handle special variables.

Global Scalar Special Variables

The following lists all scalar special variables, including both special character and English forms:

$_ Default input and pattern matching content.
$ARG
$. The current line number of the last file handle read.
$NR
$/ Input record separator, defaults to the newline character. If this variable is set to undef, it will read until the end of the file.
$RS
$, Output field separator.
$OFS
$\ Output record separator.
$ORS
$" This variable is similar to $,, but applies when interpolating array and slice values into double-quoted strings (or similar interpolated strings). Defaults to a space.
$LIST_SEPARATOR
$; The separator used when emulating multidimensional arrays. Defaults to "\034".
$SUBSCRIPT_SEPARATOR
$^L The form feed character sent to the output channel. Defaults to "\f".
$FORMAT_FORMFEED
$: The current set of characters after which a string may be broken to fill continuation fields (starting with ^) in a format. Default is "\n"".
$FORMAT_LINE_BREAK_CHARACTERS
$^A The variable used to hold formatted data before printing.
$ACCUMULATOR
$# The default number output format when printing numbers (deprecated).
$OFMT
$? Returns the status of the last external command.
$CHILD_ERROR
$! The numeric value of this variable is the value of errno, and the string value is the corresponding system error string.
$OS_ERROR or $ERRNO
$@ The error message from the eval command. If empty, it means the last eval command executed successfully.
$EVAL_ERROR
$$ The process number of the currently running Perl script.
$PROCESS_ID or $PID
$< The real user number of the current process.
$REAL_USER_ID or $UID
$> The effective user number of the current process.
$EFFECTIVE_USER_ID or $EUID
$( The real group user number of the current process.
$REAL_GROUP_ID or $GID
$) The effective group user number of the current process.
$EFFECTIVE_GROUP_ID or $EGID
$0 Contains the filename of the script being executed.
$PROGRAM_NAME
$[ The subscript of the first element of an array, defaults to 0.
$] The version number of Perl.
$PERL_VERSION
$^D The value of the debug flag.
$DEBUGGING
$^E Operating system extended error information in non-UNIX environments.
$EXTENDED_OS_ERROR
$^F The maximum file descriptor number.
$SYSTEM_FD_MAX
$^H The syntax check status activated by the compiler.
$^I The value of the built-in controlling editor.
$INPLACE_EDIT
$^M The size of the alternate memory pool.
$^O The operating system name.
$OSNAME
$^P An internal variable specifying the current debug value.
$PERLDB
$^T The time the script started running in seconds counted from the new century.
$BASETIME
$^W The current value of the warning switch.
$WARNING
$^X The name of the Perl binary executable.
$EXECUTABLE_NAME
$ARGV The current filename when reading from the default file handle.

Global Array Special Variables

@ARGV The list of command-line arguments passed to the script.
@INC The list of directories to search when importing modules.
@F The array input of the command line.

Global Hash Special Variables

%INC

The hash %INC contains all files included with do or require statements. The key is the filename, and the value is the path to the file.

%ENV

Contains the current environment variables.

%SIG

The signal list and how they are handled.

Global Special File Handles

ARGV

A special file handle that iterates over all filenames in the array variable @ARGV.

STDERR

Standard error output handle.

STDIN

Standard input handle.

STDOUT

Standard output handle.

DATA

The special file handle references any content after the __END__ marker in the file, including the script content. Or it references all content after the __DATA__ marker in a file; __DATA__ exists as long as you read data in the same package.

_ (underscore)

A special file handle used to cache file information (fstat, stat, and lstat).

Global Special Constants

__END__

The logical end of the script; the following text is ignored.

__FILE__

The current filename.

__LINE__

The current line number.

__PACKAGE__

The current package name; the default package name is main.

Regular Expression Special Variables

$n

Contains the nth substring of the last pattern match.

$&

The string of the previous successful pattern match.

$MATCH

$`

The content before the substring of the previous successful match.

$PREMATCH

$'

The content after the substring of the previous successful match.

$POSTMATCH

$+

The last bracket matching the format of the previous regular expression search. For example:

/Version: (.*)|Revision: (.*)/ && ($rev = $+);

$LAST_PAREN_MATCH

File Handle Special Variables

$|

If set to zero, the function fflush is automatically called after each call to write or print, flushing the written content back to the file.

$OUTPUT_AUTOFLUSH

$%

The current output page number.

$FORMAT_PAGE_NUMBER

$=

The current page length. Defaults to 60.

$FORMAT_LINES_PER_PAGE

$-

The number of lines remaining on the current page.

$FORMAT_LINES_LEFT

$~

The name of the current report output format. The default value is the file handle name.

$FORMAT_NAME

$^

The name of the current report header format. The default value is the file handle name with the suffix "_TOP".

$FORMAT_TOP_NAME

Other Extensions