BrowserUk has asked for the wisdom of the Perl Monks concerning the following question:

I have been seeing lots of progs and subs that start:

my $p1 = shift; my $p2 = shift; my $p3 = shift;

instead of  my ($p1, $p2, $p3) = @_;?

Are these totally equivalent and the differences are purely author preference?

Totally equivalent, but the @_ version didn't come along until later and there has been no reason to change it?

I am missing something subtle thats makes the difference?

Replies are listed 'Best First'.
Re: Getting parameters in subs
by Anonymous Monk on Jun 16, 2002 at 09:53 UTC
    See this node for a previous discussion on this topic.

      Thanks for the reference, sorry I didn't locate that myself.

      Good discussion, if a little over my head in places. Would have liked to have seen some conclusions drawn, but I guess like so many things in Perl, it more a case of context and/or taste than one is 'better' than the other.

Re: Getting parameters in subs
by Beatnik (Parson) on Jun 16, 2002 at 10:13 UTC
    Just to give you the basic stuff... shift removes the first element from an array and returns it. If no array is provided, it uses @_. So, yes, they are both kinda equivalent except that with my ($p1,$p2,$p3) = @_; you drop the remaining elements in the array and with shifting, you preserve the remaining elements. (my bad)</B<

    Greetz
    Beatnik
    ... Quidquid perl dictum sit, altum viditur.

      Hi,
      Sorry, but this is not exact. Doing

      my ($a,$b) = @_;
      you do not drop anything. Just try this:
      sub test1 { my ($a) = @_; print "\$a = $a\n"; print "\@_= (",join(",",@_),")\n"; } sub test2 { my $a = shift; print "\$a = $a\n"; print "\@_= (",join(",",@_),")\n"; } test1(1,2,3,4,5,6,7); test2(1,2,3,4,5,6,7);
      the call to <emph>test1</emph> prints
      $a = 1 @_= (1,2,3,4,5,6,7)
      while the one to <emph>test2</emph> prints:
      $a = 1 @_= (2,3,4,5,6,7)

      The basic difference should be obvious from the above examples: assigning @_ does not modify @_ (that is obviously consistent with standard assigement semantics), while using shift physically modify @_ </>

      Cheers


      Leo TheHobbit