Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between `shift` and `@_` in a subroutine?

Tags:

perl

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?

like image 272
user1032613 Avatar asked Sep 27 '12 18:09

user1032613


People also ask

What is shift in Perl subroutine?

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.

What does @_ mean 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...

How to pass arguments to subroutine in Perl?

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.


1 Answers

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 ) = @_;
}
like image 182
TJ B Avatar answered Nov 11 '22 15:11

TJ B