Perl has a large number of special, predefined variables. They are used in special circumstances and provide shortcuts to interact with the programming environment. Many special variables use punctuation characters after the variable indicator.
Every item of current input is put into this variable, for example, line input from keyboard or a filehandle.
# run this script and enter something on the keyboard # type 'control c' to quit while (<STDIN>) { print $_; }
$_
is also the default variable when no other variable is given as an argument. The following script has the same effect as the preceding one. If no value is given to print
, whatever is in $_
will be taken. In this case, $_
happens to hold the keyboard input.
# run this script and enter something on the keyboard # type 'control c' to quit while (<STDIN>) { print; }
All command line arguments (that is, everything entered on the command line following the script name) will be placed in this array. For example, if the script is started as follows,
perl my_script.pl "Hello, world!" 5 times
then @ARGV
would contain 3 items:
$ARGV[0] --> Hello, world!
$ARGV[1] --> 5
$ARGV[2] --> times
This array contains all parameters passed to a function. Scalars, arrays, and hashes are conflated into one flat array in the order they appear in the function call.
call_my_function($val_1, $val_2, @val_3); ... sub call_my_function($val_1, $val_2, @val_3) # the function prototype is just a placeholder { my $val_1 = shift; # assign function arguments to local variables my $val_2 = shift; my @val_3 = @_; ... }
If used in a string context, it returns the error string of a system call. This is commonly used to trap an error when a filehandle failed to open a file for reading or writing. For example,
open(FILE, "<myFile.txt") or print $! . "!\n";
If the file did not exist, an error message would be put into the default variable $! that could then be printed. The message would read something like
No such file or directory!