Forum Moderators: coopster & phranque

Message Too Old, No Replies

Why use shift instead of $var = $ [0]?

         

csdude55

9:10 pm on Dec 1, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I see this in examples everywhere:

sub foo {
$var = shift;
# do stuff
}

It took me awhile to figure out that $var becomes the first param sent to the subroutine; eg, if they do this:

foo('bar');

then $var equals 'bar'.

But why use shift instead of the more obvious $var = $_[0];? It's both shorter and more obvious, and they bench test to the same speed. And since shift actually modifies @_ then it can confuse things down the road.

Is there another reason, or is it just a personal preference thing?

Brett_Tabke

1:38 am on Dec 2, 2022 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



because you can send multiple params down to the sub. Why get confused?
&Foo($zip,$rip,$tip)

sub Foo {
$z =shift;
$r=shift;
$t=shift;
}

or
&Foo($zip,$rip,$tip)

sub Foo {
($z,$r,$t) =@_;
}


I think it is cleaner and easier to maintain than $_[0];

csdude55

5:51 am on Dec 2, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



As a rule of thumb, when I'm in doubt I bench test, and when it's the same then I go for the shorter code. In your example, using @_ is 37% smaller, so faster to open.

What I don't like about shift is that it opens up the possibility to make a mistake later on. If, for example, you have:

Foo($zip);

sub Foo {
$z = shift;
}

and then later in the code you mistakenly use $_[0], it's going to be empty instead of the value of $zip.

So I guess it all comes down to personal preference with no specific advantage, but to me there are just too many cons so I'm not really sure why it became the popular choice. is it a carry over from C or something? I know a lot of Perl is based on C.