Therefore, if you called a function with two arguments, those
would be stored in $_[0] and $_[1].
The array @_ is a local array, but its
elements are aliases for the actual scalar parameters.
In particular, if
an element $_[0] is updated, the
corresponding argument is updated (or
an error occurs if it is not
updatable).
If an argument is an array
or hash element which did not exist
when the function was called, that
element is created only when (and if)
it is modified or a reference to it is
taken. (Some earlier versions of Perl
created the element whether or not the
element was assigned to.) Assigning to
the whole array @_ removes that
aliasing, and does not update any
arguments.
You can also use shift for individual variables in most cases:
$var1 = shift;
This is a topic in which you should research further as Perl has a number of interesting ways of accessing outside information inside your sub routine.
Also if a function returns an array, but the function is called without assigning its returned data to any variable like below. Here split() is called, but it is not assigned to any variable. We can access its returned data later through @_:
In a subroutine or when you call a function in Perl, you may pass the parameter list. In that case, @_ is can be used to pass the parameter list to the function:
sub Average{
# Get total number of arguments passed.
$n = scalar(@_);
$sum = 0;
foreach $item (@_){
# foreach is like for loop... It will access every
# array element by an iterator
$sum += $item;
}
$average = $sum / $n;
print "Average for the given numbers: $average\n";
}
Function call
Average(10, 20, 30);
If you observe the above code, see the foreach $item(@_) line... Here it passes the input parameter.
Never try to edit to @_ variable!!!! They must be not touched.. Or you get some unsuspected effect. For example...
my $size=1234;
sub sub1{
$_[0]=500;
}
sub1 $size;
Before call sub1 $size contain 1234. But after 500(!!) So you Don't edit this value!!! You may pass two or more values and change them in subroutine and all of them will be changed! I've never seen this effect described. Programs I've seen also leave @_ array readonly. And only that you may safely pass variable don't changed internal subroutine
You must always do that:
sub sub2{
my @m=@_;
....
}
assign @_ to local subroutine procedure variables and next worked with them.
Also in some deep recursive algorithms that returun array you may use this approach to reduce memory used for local vars. Only if return @_ array the same.