Open In App

Special variables in Perl

Improve
Improve
Like Article
Like
Save
Share
Report

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/perl
while ( $abc = <> ) 
{
    print lc($abc);
}


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




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


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.




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


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.




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


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.




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


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.




#!/usr/bin/perl
  
local $/;           # enable "slurp" mode
local $_ = <FH>;    # whole file now here
s/\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.

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.




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


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.



Last Updated : 21 Nov, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads