in reply to difficulty in understanding use of @_ and shift in a subroutine
Hello masood91, and welcome to the Monastery!
In Perl, arguments are passed into subroutines by reference (as opposed to a language like C, in which arguments are passed by value). The special variable @_ contains aliases to the arguments passed in, so you can use them directly:
sub abc { $_[0] = 42; }
but that changes the variables outside of the subroutine. For example, if the above were called as follows:
my $x = 17; abc($x);
then after the subroutine call $x would contain 42. Since this is usually not what you want, it is standard practice to simulate pass-by-value by copying the arguments as the first statement in the subroutine:
sub abc { my ($x, $y, $z) = @_; }
or (less commonly):
sub abc { my @args = @_; }
(Note that @_ is an array variable.) To remove the first element from an array and get its value, Perl provides shift:
my $num = shift @array;
After this operation the first element in @array has been removed and stored in the scalar variable $num. Now, within a subroutine, if shift is used without an argument then it automatically applies to @_. Hence, another common idiom is:
sub abc { my $x = shift; my $y = shift; my $z = shift; }
which does the same as:
sub abc { my ($x, $y, $z) = @_; }
except that with shift the elements are also removed from the @_ array.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|