Special variables in Perl

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Providing some input 
while ( <> ) 
    # Printing the default value 
    # stored in $_
    print lc($_); 
}

chevron_right


This is the same as

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
while ( $abc = <> ) 
{
    print lc($abc);
}

chevron_right


Following is an example of the above mentioned special variable in working format:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
foreach ('Mango', 'Orange', 'Apple')
{
   print($_);
   print("\n");
}

chevron_right


Output:
The output of the above code will be:

Mango
Orange
Apple

Types of Special Variables

Special Variables can be categorized on the basis of their usage and nature. These are:

  1. Regular Expression Special Variables
  2. File handle Special Variables
  3. Global Scalar Special Variables
  4. Global Array Special Variables
  5. Global Hash Special Variables
  6. Global Special Constants
  7. Global Special File handles

Regular Expression Special Variables

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

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
# Declaring local string
local $_ = 'abcdefghi';
  
# Pattern matching
/def/;
  
# Printing the matched pattern
print "$&\n";  

chevron_right


Output:

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
# Declaring local string
local $_ = 'abcdefghi';
  
# Pattern matching
/def/;
  
# Prematching the pattern
print "$`:$&\n";  

chevron_right


Output:


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
# Declaring local string
local $_ = 'abcdefghi';
  
# Pattern matching
/def/;
  
# Postmatching the pattern
print "$&:$'\n";  

chevron_right


Output:

def:ghi

File handle Special Variables

$|, $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.

Global Scalar Special Variables

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.


filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
local $/;           # enable "slurp" mode
local $_ = <FH>;    # whole file now here
s/\n[ \t]+/ /g;

chevron_right


‘$, ‘, $ 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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.

chevron_right


Here, it is said that it’s meaningless because here this variable($!) is unrelated to the outcome of open() operator.

Global Array Special Variables

@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.

Global Hash Special Variables

%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.

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
my $doo = 1;
$ENV{'car'} = \$doo;
  
if( ref $ENV{'car'} ) 
{
    print "Ver 5.18.0";
else
{
    print "Ver 5.18.0";
}

chevron_right


Output:


Ver 5.18.0

%SIG : To update the value of various signals this hash is used. It contains signal handlers for signals.

Global Special File handles

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.

Global Special Constants

__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.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.