Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between Perl's shift versus assignment from @_ for subroutine parameters?

Let us ignore for a moment Damian Conway's best practice of no more than three positional parameters for any given subroutine.

Is there any difference between the two examples below in regards to performance or functionality?

Using shift:

sub do_something_fantastical {
    my $foo   = shift;
    my $bar   = shift;
    my $baz   = shift;
    my $qux   = shift;
    my $quux  = shift;
    my $corge = shift;
}

Using @_:

sub do_something_fantastical {
    my ($foo, $bar, $baz, $qux, $quux, $corge) = @_;
}

Provided that both examples are the same in terms of performance and functionality, what do people think about one format over the other? Obviously the example using @_ is fewer lines of code, but isn't it more legible to use shift as shown in the other example? Opinions with good reasoning are welcome.

like image 237
cowgod Avatar asked Jan 06 '09 02:01

cowgod


1 Answers

There's a functional difference. The shift modifies @_, and the assignment from @_ does not. If you don't need to use @_ afterward, that difference probably doesn't matter to you. I try to always use the list assignment, but I sometimes use shift.

However, if I start off with shift, like so:

 my( $param ) = shift;

I often create this bug:

 my( $param, $other_param ) = shift;

That's because I don't use shift that often, so I forget to get over to the right hand side of the assignment to change that to @_. That's the point of the best practice in not using shift. I could make separate lines for each shift as you did in your example, but that's just tedious.

like image 84
brian d foy Avatar answered Sep 28 '22 09:09

brian d foy