Re: Shift vs. @_



Adam W wrote:

I was wondering when it is appropriate to do multiple shifts on
parameters passed to a subroutine and when it is appropriate to just
feed it @_.

For example, you have:

&fancy_sub($a, $b, $c, @d);

Don't use the & to call subroutines unless you know what that does and
you want those two side-effects. In all other cases, leave the & off.

perldoc perlsub

for more information

Is it better (I'm leaving this term vague on purpose) to write:

sub fancy_sub {
my($a, $b, $c, @d) = @_;
...do some fancy stuff...
}

or

sub fancy_sub {
my $a = shift;
my $b = shift;
my $c = shift;
my @d = @_;
...do some fancy stuff...
}


It is pointless to ask which is "better" when the two algorithms do not
do the same thing. The first makes copies of the values in @_. The
latter removes elements from @_ and assigns them to the individual
variables. That is, in the first, @_ remains as it was, containing
all the arguments passed into the script. In the second, @_ has lost
its first three elements.

So the question is not "which is better?", but rather "Which do you
want?" That is not a question that has a generic answer.

Paul Lalli

.



Relevant Pages

  • Re: passing database data to a sub
    ... > I'm not sure of the difference, why isn't it a subroutine? ... > sure about this 'shift' thing anyway :-) ... > sub teardown ... > # Setup the template to use for the output. ...
    (perl.beginners)
  • Re: Replacing a line
    ... #Using core module Tie::File to process a file in this subroutine ... sub process_one_file { ... $cpp_file = shift; ... for (@array) #Each line should come one by one ...
    (comp.lang.perl.misc)
  • subroutine in LWP - in order to get 700 forum threads
    ... sub get_threads { ... my $page = shift; ... push @links, values %attr; ... This must get a subroutine - doesn t it? ...
    (perl.beginners)
  • Re: use one subroutines variable value in another subroutine inside a module.
    ... my $self = shift; ... the get_course_info subroutine. ... sub load_school_template ... Now I've answered the question you asked I'll compose another follow- ...
    (comp.lang.perl.misc)
  • RE: passing database data to a sub
    ... Second, GetOfficersis called as a subroutine, not as a method of an object. ... I not completely sure about this 'shift' thing anyway :-) ... sub teardown ... # Note...this subroutine uses the template 'db_mainmenu.tmpl.htm' to give ...
    (perl.beginners)