What is the meaning of @_
in Perl?
@ is used for an array. 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...
There is a strange scalar variable called $_ in Perl, which is the default variable, or in other words the topic. In Perl, several functions and operators use this variable as a default, in case no parameter is explicitly used. In general, I'd say you should NOT see $_ in real code.
=~ is the Perl binding operator. It's generally used to apply a regular expression to a string; for instance, to test if a string matches a pattern: if ($string =~ m/pattern/) {
The variables are shown ordered by the "distance" between the subsystem which reported the error and the Perl process...$@ is set if the string to be eval-ed did not compile (this may happen if open or close were imported with bad prototypes), or if Perl code executed during evaluation die()d.
perldoc perlvar is the first place to check for any special-named Perl variable info.
Quoting:
@_
: Within a subroutine the array@_
contains the parameters passed to that subroutine.
More details can be found in perldoc perlsub (Perl subroutines) linked from the perlvar:
Any arguments passed in show up in the array
@_
.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.
Usually, you expand the parameters passed to a sub using the @_
variable:
sub test{ my ($a, $b, $c) = @_; ... } # call the test sub with the parameters test('alice', 'bob', 'charlie');
That's the way claimed to be correct by perlcritic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With