Perl special variables - explained with examples

Perl developers love to type less and Perl provides an abundant set of special variables to support the same. These variables generally use special characters like punctuation marks etc. so that developers can easily identify them from the normal variables. Following is a list of few Perl special variables which you as a Perl developer need to know.

Perl Special Global variables

$_ : Implicit variable

foreach my $item (@items) {
    print $item;
}

$_ will implicitly be used whenever a variable is omitted, so above loop can be rewritten as:

foreach (@items) {
    print ;
}

@_ : arguments for a subroutine are stored in this array. One way to access them within your subroutine could be:

&max(23, 42);sub max {
my ($a, $b) = @_;
 
  if ($a > $b) {
   return $a;
  }
  return $b;
}

$0 : contains name of the current Perl program being executed. e.g. if the following code is part of main.pl, it will print the file name:

print $0, "\n"; #prints: main.pl

%ENV : contains a copy of the current environment variables:

foreach (keys %ENV) {
     print $_, "::", $ENV{$_}, "\n";
}

Above may generate a list of environment variables and their values as :

PATH::/usr/bin:/usr/local/bin
HOME::/home/pankaj
TERM::Linux

%INC : hash containing entries for the files that have been included using do, use or require:

#! /usr/bin/perl
use warnings;
use 5.010;
foreach  (keys %INC) {
    print $_, "::", $INC{$_}, "\n";
}

This might print something like this on your machine:

warnings.pm::/usr/share/perl5/warnings.pm
feature.pm::/usr/share/perl5/feature.pm

@INC : list of places where Perl looks for the files included using do, use or require:

print "@INC";

This might print something like this on your machine:

/usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .

%SIG : Hash containing signal handlers. The following program sets the user defined custom signal handler for interrupt signal - INT:

sub my_int_handler {
    die "interrupted, exiting...\n";
}

$SIG{'INT'} = 'my_int_handler';

$#<array_name> : points to the last element of an array:

@days = ('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
print "The last element in \@days array is: ", $days[$#days];  #prints saturday


Perl Special variables related to Sorting

$a and $b : Perl has it own default way of sorting list, but if you want to provide your own sorting condition - Perl requires you to provide a subroutine which automatically assigns $a and $b to be the two variables upon which comparison will be performed. For example to sort a list of numbers numerically the following subroutine would be required:

sub by_number {
    if ($a < $b) { -1 } elsif ($a > $b) { 1 } else  { 0 }
} my @result = sort by_number @list_numbers;

Above code can also be written in an inline precise format using Ship operator which internally translates to the if block as explained above:

my @result = sort {$a <=> $b} @list_numbers;


Perl Special Command line variables

<> : diamond operator - used to read lines one by one from the files specified on the command line, if no files are specified, it reads from the STDIN (standard input). Run the following program from the command line as : 'perl main.pl 1.txt 2.txt'

while(<>) {
    chomp;
    print "It was $_ that I saw!\n";
}

@ARGV : command line arguments are stored in ARGV array. A word of caution for C programmers: $ARGV[0] is what you get in C from argv[1] :

foreach (@ARGV) {
    print;
    print "\n";
}

If main.pl contains the above code, then executing 'perl main.pl pankaj pal is a good boy' over the command line will print this:

pankaj
pal
is
a
good
boy

$ARGV : contains the name of the current file being read while we are reading input test using a diamond operator:

while(<>) {
    print "The current file being read is $ARGV \n";
}

$^I : inplace edit variable is used to specify the backup file name while we are trying to edit a file. The following code reads lines from a file (e.g. test.txt) and renames it to test.txt.bak. Then it executes the regular expression over those lines one by one and writes down the modified text into test.txt. At the end of execution of perl program, you will have the modified text in text.txt, while the original content will still be preserved in text.txt.bak.

$^I = ".bak";
while(<>) {
    s/^Author:.*/Author: Pankaj Pal/;
    print;
}

Perl special Status variables

$! : returns the error string for the last system call used. Using it with die tags along the file name and the line number:

open FH, "<", "hello.txt" or die "Cannot open file for reading : $!";

If the file hello.txt doesnt exist, it will print something like this:

Cannot open file for reading : No such file or directory at main.pl line 3.

$? : exit status of most recent system call or backquoted command:

$var = `datel`;
print "Error returned by above command is :", $?;

This will print :

Error returned by above command is :-1

$@ : error message returned from eval:

my $barney = eval { $fred / $dino }; #NaN
print "I couldn't divide by \$dino: $@" if $@;

This will print:

I couldn't divide by $dino: Illegal division by zero at main.pl line 3.

Perl Special Regular expression variables

$`, $&, $' : Automatic match variables filled up while evaluating a Perl regular expression. $& is the part matched by regular expression, $` is the pre-matched part, while $' is the post-matched part:

if ("Hello World, there" =~ /\s(\w+),/) {
    print "That was ($`)($&)($')\n";  # will print: (Hello)( World,)( there)
}

This is not a comprehensive list of Perl special variables by any means, but are definitely the most used ones. For detailed explanation use 'perldoc perlvar' command. Do reply back with comments / suggestions...

comments powered by Disqus