Perl comes with a whole bunch of cryptically-named built-invariables, which clever Perl programmers exploit to reduce the number oflines of code in their scripts. This article examines some of the morecommonly-used special variable in Perl, with examples and illustrations ofhow they may be used.
When reading data from files, Perl allows you to obtain the name of the file with the $ARGV variable, and the line number with the $. variable. This makes it easy to obtain information on which file (and which line of the file) is under the gun at any given moment. Consider the following example, which demonstrates:
#!/usr/bin/perl
# read a file and print its contents
while (<>)
{
# for each line, print file name, line number and contents
print $ARGV, ",", $., ": ";
print;
}
Here's an example of the output:
multiply.pl,1: #!/usr/bin/perl multiply.pl,2: multiply.pl,3: # multiply two numbers multiply.pl,4: sub multiply() multiply.pl,5: { multiply.pl,6: my ($a, $b) = @_; multiply.pl,7: return $a * $b; multiply.pl,8: } multiply.pl,9: multiply.pl,10: # set range for multiplication table multiply.pl,11: @values = (1..10); multiply.pl,12: multiply.pl,13: # get number from command-line multiply.pl,14: foreach $value (@values) multiply.pl,15: { multiply.pl,16: print "$ARGV[0] x $value = " . &multiply($ARGV[0], $value) . "\n"; multiply.pl,17: }
Note, however, that the line number returned by $. does not automatically reset itself when used with multiple files, but rather keeps incrementing. In order to have the variable reset to 0 every time a new file is opened, you need to explicitly close() the previous file before opening a new one.
The $0 variable returns the file name of the currently-running Perl script, as illustrated below:
#!/usr/bin/perl
# print filename
print "My name is $0";
Here's the output:
My name is /tmp/temperature.pl
The $$ variable returns the process ID of the currently-running Perl process, as below:
#!/usr/bin/perl
# print process ID
print "This script is owned by process ID $$. Collect them all!";
Here's the output:
This script is owned by process ID 2209. Collect them all!
Finally, the special variable $] always contains information on the Perl version you are currently running. So, for example, the program
#!/usr/bin/perl
# print Perl version
print "Running Perl $]";
might return something like this:
Running Perl 5.008
This, coupled with the $0 and $$ variables explained earlier, can come in handy when debugging misbehaving Perl programs,
#!/usr/bin/perl
# check for error
if ($error == 1)
{
# write to error log with script name, PID and Perl version
open (FILE, ">>/tmp/error.log");
print FILE "Error in $0 (perl $] running as PID $$\n";
close (FILE);
}
or even to perform version checks to ensure that your code only works with a specific Perl version.
#!/usr/bin/perl
# check version
# display appropriate message
if ($] < 5.0)
{
die("You need a more recent version of Perl to run this program");
}
else
{
print "This is Perl 5 or better";
}