I always use @_[0]
to get the first parameter and use @_[1]
to get the second one. But when I search up code snippets online, I find many people like to use the shift
keyword. I don't find the shift
keyword being intuitive at all. Is there any functional differences between these two?
shift() function in Perl returns the first value in an array, removing it and shifting the elements of the array list to the left by one. Shift operation removes the value like pop but is taken from the start of the array instead of the end as in pop.
@ 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...
Passing Arguments to a Subroutine You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.
Yes, there is a difference between the two.
shift
would change the @_
(You could argue this would be an operation that would make shift slower)
$_[0]
or $_[1]
is just assignment and would not change @_
at all.
The aesthetic way of writing this is :
sub this_is_better {
my ( $foo, $bar, $hey, $whoa, $doll, $bugs ) = @_;
}
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