in reply to why can't I shift a split?

It's funny, I was trying to explain why it's not working, and I got really confused myself! LOL Here's what I began to write:

When you do shift split, the shift() function not only returns the first element of an array, but it also tries to REMOVE that element from an array, which it must be able to do. Demo:

#!/usr/bin/perl use strict; use warnings; my @A = (234, 405, 55, 1900); print "\n", shift(@A); # Prints 234 #print "\n", shift(234, 4, 55, 1900); # Error: Can't overwrite +the array, because it's fixed. #print "\n", shift( split(/\+/, '12+34+56+78') ); # Error: Can't over +write the array, because it's fixed. my $X = 3; print "\n", INCREMENT($X); # Prints 4. #print "\n", INCREMENT(3); # Error: Can't overwrite 3, because it's + fixed. print "\nNOW: $X"; # Prints 4. No error. print "\n", INCREMENT( $X + 3 ); # Prints 8. No error. print "\nTHEN: $X"; # Prints 4. No error. #print "\n", shift( @A, split(/\+/, '12+34+56+78') ); # Error. Can't +do this. # Kind of weird. That's not what I expected. :P exit; sub INCREMENT { ++$_[0]; }

See also: lvalue

Replies are listed 'Best First'.
Re^2: why can't I shift a split?
by johngg (Canon) on Aug 27, 2022 at 15:16 UTC
    #print "\n", shift(234, 4, 55, 1900);        # Error: Can't overwrite the array, because it's fixed.

    shift works by default on @_ in a subroutine (also true of pop) so you could use an on-the-fly sub to operate on a list.

    johngg@aleatico:~$ perl -Mstrict -Mwarnings -E ' my @arr = ( 234, 405, 55, 1900 ); say shift @arr; say sub { shift }->( 234, 405, 55, 1900 ); $_ = q{ab,ce ef}; say sub { shift }->( split m{,} );' 234 234 ab

    I hope this is helpful.

    Update: Corrected typo, s{on (?=by default)}{}.

    Cheers,

    JohnGG