For a beginner, Perl can be a frightening language. This is largely due the numerous special variables used in perl. Once a programmer understands the special variables, he/she begins to appreciate the beauty and strength of Perl.
The special variable $_
$_ functions as a default variable. $_ needs to be initialized implicitly or explicitly before it can used.
$_ = "default value";
print; # this will print the value of $_
Note that I did not specify which variable to print. When no variable is provided where a variable is expected, the $_ special variable is used. Here’s another example:
while()
print $_;
This program will reprint whatever the user types. takes the input from the an external device such as a keyboard. This data must be assigned to a variable before it can be used. Since I did not specify a variable, the input is automatically stored in $_. If I remove the $_ from the second line, this program will still function properly since print; will print the value of $_ by default as seen in the previous example.
$_[], a subscript of @_ special variable
It is common for Perl beginners to confuse $_ with $_[]. In fact, $_[] is a subscript of @_ and it has nothing to do with the scalar variable $_.
@_ special variable contains a list of all the arguments passed to a subroutine. $_[argument number] is a way of accessing an individual argument.
sub printarguments
print join('-',@_);
print "\nThe second argument was $_[1]";
printarguments('one','two','three');
Perl indexes begin from 0. Therefore $_[0] accesses the first argument, $_[1] accesses the second argument, and so on.