WSBT
WSBT

Reputation: 36333

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

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?

Upvotes: 7

Views: 2904

Answers (2)

squiguy
squiguy

Reputation: 33370

As stated in the documentation, shift without using an explicit array simply takes the next parameter from @_ in the subroutine locally by removing arguments from the beginning and shifting the remaining elements to the front.

Upvotes: 0

TJ B
TJ B

Reputation: 167

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 ) = @_;
}

Upvotes: 15

Related Questions