develooper Front page | perl.beginners | Postings from May 2012

Re: shift vs @_

Thread Previous
From:
Rob Dixon
Date:
May 20, 2012 08:30
Subject:
Re: shift vs @_
Message ID:
4FB90E22.1010201@gmx.com
On 20/05/2012 16:16, John SJ Anderson wrote:
> On Sunday, May 20, 2012 at 11:09 AM, sono-io@fannullone.us wrote:
>>
>> Are there any differences between these two idioms if only one or
>> zero arguments are passed to them?
>>
>> my ($mode) = @_;
>>
>> my $mode = shift;
>>
>> If so, why would you chose one over the other?
>>
>> It seems to me that they behave exactly the same for this purpose,
>> but maybe there's a subtle difference that I'm not aware of.
>
> 'shift' will modify @_; assignment won't. Run this:
>
> #! perl
>
> use strict;
> use warnings;
> use feature 'say';
>
> use Data::Printer;
>
> sub shifter {
>    my $var = shift;
>    say "SHIFT";
>    p $var;
>    p @_;
>    say '';
> }
>
> sub assigner {
>    my( $var ) = @_;
>    say "ASSIGN";
>    p $var;
>    p @_;
>    say '';
> }
>
> shifter( 'foo' );
> assigner( 'foo' );

Hello

This isn't the best demonstration of the two behaviours as p() outputs
to stderr by default and the diganostics will be out of sync with the
text output using print(). Change the 'use' line to

    use Data::Printer (output => 'stdout');

to see things as nature intended.

What John is trying to say is that the two methods have identical
results except that shift() modifies @_ whereas a list assignment leaves
it intact. This may or may not be significant depending on the application.

My own appreciation of this is that the classical method is to use
shift(), but popular usage is moving towards a list assignment. One
significant exception is that object methods are passed the object as
the first parameter, and it makes a lot of sense to write

   my $self = shift;
   my ($arg1, $arg2) = @_;

so that the explicit method arguments are separated from the object.

HTH,

Rob

Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About