Re: Shift Question



Mulander wrote:
> If I understood you question properly you want to know why people use
> shift in subrutines and how does shift work.
>
> I will try to make it short:
> shift works on lists, it removes the first element of the list

perldoc -q "What is the difference between a list and an array"

You can't use shift() on a list, only on an array:

$ perl -le'my $x = shift qw(10 11 12 13 14)'
Type of arg 1 to shift must be array (not list) at -e line 1, at EOF
Execution of -e aborted due to compilation errors.


> and returns it as a lvalue

The term 'lvalue' has a specific meaning in Perl (and CS) which usually means
something that can be assigned to. Functions like substr() and vec() are
lvalue subs while shift() is not.

$ perl -le'my $x = "abc"; substr( $x, 2 ) = "xyz";'
$ perl -le'my @x = qw"a b c"; shift( @x ) = "xyz";'
Can't modify shift in scalar assignment at -e line 1, near ""xyz";"
Execution of -e aborted due to compilation errors.


>
> [snip]
>
> Hope this will clear some things up, you can check also:
> perldoc -f shift
> perldoc -f unshift
> perldoc -f pop
> perldoc -f push

And also:

perldoc -f splice
perldoc perlsub



John
--
use Perl;
program
fulfillment
.



Relevant Pages

  • Re: Perl translation needed for simple bat file
    ... perldoc -q "command line" ... The command line arguments will be in the @ARGV array. ... You can either access these directly or use the shift operator to get ...
    (comp.lang.perl.misc)
  • Re: Joining/Merging AoA
    ... push my @c, [@{shift @a}]; ... perldoc -f shift ... better off starting a new thread on understanding references. ...
    (perl.beginners)
  • Shift Question
    ... shift in subrutines and how does shift work. ... shift works on lists, it removes the first element of the list (the 0 ... perldoc -f unshift ...
    (perl.beginners)
  • Re: populating a Hash
    ... perldoc -q quoting ... sub errorMessage { ... shift() removes the first element of an array and returns it. ... If you do really need a hash then: ...
    (perl.beginners)
  • Re: Shift Question
    ... > shift in subrutines and how does shift work. ... > shift works on lists, it removes the first element of the list (the 0 ... > perldoc -f unshift ... Additionally a very common idiom and where you may be seeing this so ...
    (perl.beginners)