Search code examples
perlsubroutineshift

Assigning shift to a variable


Other thread that I read: What does assigning 'shift' to a variable mean?

I also used perldoc -f shift:

shift ARRAY
shift

Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. If there are no elements in the array, returns the undefined value. If ARRAY is omitted, shifts the @_ array within the lexical scope of subroutines and formats, and the @ARGV array outside of a subroutine and also within the lexical scopes established by the eval STRING, BEGIN {}, INIT {}, CHECK {}, UNITCHECK {} and END {} constructs.

See also unshift, push, and pop. shift and unshift do the same thing to the left end of an array that pop and push do to the right end.

I understand outside of subroutines, the array is @ARGV, and inside arguments are passed through @_

I've read countless tutorials on how to use the shift function, but it's always about arrays, and how it removes the first element at the beginning of the array and returns it. But I see sometimes

$eg = shift;
~do more things here~

It seems as if nothing is making sense to me, and I feel like I can't continue reading more until I understand how this works as it's a "basic building block" to the language.

I'm not quite sure if an example of code is needed, as I believe the same principles apply to all programs that use shift. But if wrong I can provide some examples of code.


Solution

  • It depends on your context.

    In all cases, shift removes the element at list index 0 and returns it, shifting all remaining elements down one.

    Inside a sub, shift without an argument (bare shift) operates on the @_ list of subroutine parameters.

    Suppose I call mysub('me', '22')

     sub mysub {
        my $self = shift;  # return $_[0], moves everything else down, $self = 'me', @_ = ( '22' )
        my $arg1 = shift;  # returns $_[0], moves everything down, $arg1 = '22', @_ = ()
    
     }
    

    Outside a sub, it operates on the @ARGV list of command line parameters.

    Given an argument, shift operates on that list.

     my @list1 = ( 1,2,3,4,5 );
     my $first = shift @list1; # $first = 1, @list1 = (2,3,4,5)