Special variables in Perl

21 Nov, 2019
Special Variables in Perl are those which are already defined to carry out a specific function when required. The differentiating factor between a special Variable in Perl and a random character is the use of Punctuation mark after the variable, these could be @, $ or %, etc, for example, $_.
Perl Variables helps a developer in saving time since these are generally shortcuts to bigger commands in English.
Note: The most common special variable is $_, which is used to store the default input.
Look at the following codes to get an idea about this special variable:
# Providing some input while ( <> ) {     # Printing the default value     # stored in $_    print lc($_); }
This is the same as
#!/usr/bin/perlwhile ( $abc = <> ) {    print lc($abc);}
Following is an example of the above mentioned special variable in working format:
#!/usr/bin/perlforeach ('Mango', 'Orange', 'Apple'){   print($_);   print("\n");}
Mango
Orange
Apple

Special Variables can be categorized on the basis of their usage and nature. These are:
Regular Expression Special VariablesFile handle Special VariablesGlobal Scalar Special VariablesGlobal Array Special VariablesGlobal Hash Special VariablesGlobal Special ConstantsGlobal Special File handles
Regular Expression Special Variables
File handle Special Variables
Global Scalar Special Variables
Global Array Special Variables
Global Hash Special Variables
Global Special Constants
Global Special File handles
$digit: The main function of $digit is to hold the text matched in a similar set of parentheses in the last matched pattern. However, patterns already matched in a nested block are not counted.
$&, $MATCH: Used to find the string matched in the last successful pattern search. Though Matched in a hidden block or enclosed in the current set are not counted. This is a read-only variable and is scoped dynamically.
#!/usr/bin/perl  # Declaring local stringlocal $_ = 'abcdefghi';  # Pattern matching/def/;  # Printing the matched patternprint "$&\n";  
def

$`, $PREMATCH: The string preceding a quoted string was matched with the last successful pattern match. It doesn’t count any matches enclosed within a block or eval enclosed by the current block.
#!/usr/bin/perl  # Declaring local stringlocal $_ = 'abcdefghi';  # Pattern matching/def/;  # Prematching the patternprint "$`:$&\n";  
abc:def

$’, $POSTMATCH: The string following whatever was matched by the last successful pattern match not counting any matches hidden within a block or eval enclosed by the current block.
#!/usr/bin/perl  # Declaring local stringlocal $_ = 'abcdefghi';  # Pattern matching/def/;  # Postmatching the patternprint "$&:$'\n";  
def:ghi

$|, $OUTPUT_AUTOFLUSH: If set to nonzero, this variable forces a flush after every write or print statement on the output channel that is currently being selected.
$%, $FORMAT_PAGE_NUMBER: This variable finds the currently selected output channel and the current page number.
$=, $FORMAT_LINES_PER_PAGE: This variable returns the current page length i.e. the lines which are printable of the currently selected output channel. The default value for this variable is 60.
$-, $FORMAT_LINES_LEFT: Returns the number of lines left on the page of the currently selected output channel.
$~, $FORMAT_NAME: The name of the current report format for the currently selected output channel. The default value is the name of the filehandle. For example, for STDOUT, the default format name would be STDOUT itself.
Below mentioned is the list of some of the scalar special variables. And listed corresponding English like names along with the symbolic names.$_, $ARG : Used as a default variable to accept input and to perform pattern-searching, when variable is omitted.
$., $NR : Contains the line number of the filehandle last updated. The value is reset to zero if the filehandle is closed. This variable will never move the seek pointer in the file.
$/, $RS : This is the input record separator. If $/ is undefined, the entire file is read as a single input for null value a blank is considered as a delimiter. It creates a new line by default.
#!/usr/bin/perl  local $/;           # enable "slurp" modelocal $_ = <FH>;    # whole file now heres/\n[ \t]+/ /g;
‘$, ‘, $ OFS: The Output Field Separator command is used when the user wants to print a default value between each print operator argument. The default value for this variable is undef.
$\, $ORS: The Output Record Separator command is used when the user wants to print the value at the last of the print operator arguments.
$!, $OS_ERROR or $ERRNO : Yields the current value of error no. variable if used in a numeric context.If utilized in a string context, it yields the corresponding system error string.
if (open my $fh, "<", $filename) {    # Here $! is meaningless.    ...}else {    # ONLY here is $! meaningful.    ...    # Already here $! might be meaningless.}  # Since here we might have either success or failure,# $! is meaningless.
Here, it is said that it’s meaningless because here this variable($!) is unrelated to the outcome of open() operator.
@ARGV : In a command-line argument @ARGV is the array which is used for the intended script. It is generally one value less than the total number of arguments.
 
$ perl -e 'print join( ", ", @ARGV), "\n"' a b c
a, b, c
$ perl -e 'print join( ", ", @ARGV), "\n"' a "b c" d
a, b c, d

Here, a, b, c, d represents any numeric values.

@INC: This variable can be considered as the inbuilt help array which contains the list of places to find scripts to be evaluated by the do, require, or use constructs.
    BEGIN { unshift @INC, "local/lib" };

    use lib "local/lib";
@F : When we use the -a command-line switch we use @F to split and input the lines into an array. This array needs a full package name because it is package-specific.
%INC : This variable contains the entries for the file name of each file that has been included. These entries are done via do, require or use operators.
%ENV : The hash containing your current environment.
#!/usr/bin/perlmy $doo = 1;$ENV{'car'} = \$doo;  if( ref $ENV{'car'} ) {    print "Ver 5.18.0";} else{    print "Ver 5.18.0";}
Ver 5.18.0

%SIG : To update the value of various signals this hash is used. It contains signal handlers for signals.
ARGV: ARGV is a special filehandle the file name is iterated over a command line when @ARGV is used. Generally, it is the null filehandle.
STDERR: It is the special file handle for standard error in any package.
STDIN: The special file handle for standard input in any package.
STDOUT: The special file handle for standard output in any package.
DATA: The special filehandle that refers to anything following the __END__ token in the file containing the script.
_ (underscore): The special filehandle used to cache the information from the last stat, lstat, or file test operator.
__END__: Used to show the end of a program.
__FILE__: Show the file name where it is referenced.
__LINE__: Shows the current line number
__PACKAGE__: This variable shows the package name.
perl-basics
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.