Oct 212013
 
Article Perl

The $_ variable

$_ is the default variable in perl when a variable is required, and no other variable has been explicitly specified:

  • In a while or foreach loop (that expect an array as argument)
  • When a regular expression is evaluated
  • In many intrinsic functions that expect at least one input argument

For instance, the following sample script reads lines from standard input and splits them into words:

Perl uses the $_ variable in those places where a variable is required, but no variables has been explicitly specified. Therefore, the sample code above is equivalent to the extended code:

As we can see, the implicit variable $_ has been used:

  • In the while loop
  • In the evaluation of the regex
  • In the ‘split’ function
  • In the foreach loop
  • In the ‘print’ sentence

The @_ variable

Inside a subroutine, this variable is an array that holds the arguments passed to it. For instance:

When this sample code is executed, the following output is printed:

Also note that, in the sentence “my $n = @_;”, the array variable is assigned to a scalar variable. In this case, the value assigned to $n is the number of elements in the array. This implicit behaviour can be made more explicit, writing the sentence as “my $n = scalar @_;”

The $a, $b variables

These are the variables used in the “sort” function.

The following code uses the “sort” function to print alphabetically a series of values:

With the following result printed to the screen:

But, if we want to sort those values by the number of characters in them, a custom sort function can be written as:

And the result obtained will be:

The “sort” function must determine, for every two elements in the array, which one comes first. To do this, it assigns the values of those to elements to the variables $a and $b. The function specified in curly brackets {…} references those variables to implement the desired sorting criteria.

References

Perlmonks: Perl Special vars Quick Reference

Index of posts related to Perl programming

 Posted by at 9:21 am

 Leave a Reply

(required)

(required)