gannett has asked for the wisdom of the Perl Monks concerning the following question:
I was stuck debugging a larger program but finally located the cause of the misunderstanding. The code takes one element off an array then process the rest of the array using while ( $next = pop @x) { Process element in $next }; I noticed that in some circumstances an element was being dropped. After some digging I found that the behaviour of shift and pop are not reversibly consistent in this context. The code works as expected using shift but pop stops when the element value 0 is processed.
Can anyone explain why pop behaves differently from shift in this context ?
In the demonstrator code below the array x delivers 2 elements but all the rest deliver 3 elements.
This is perl 5, version 22, subversion 1 (v5.22.1) built for darwin-thread-multi-2level on a MacBookProuse strict; my @a = ( 0,1,2,3 ) ; my @b = ( 1,2,3,4 ); my @x = ( 0,1,2,3 ) ; my @y = ( 1,2,3,4 ); my @r = reverse @a; my $next = 0 ; my $first = 0; my $first = shift @a ; print "a $#a shift ",$first,"->"; while ( $next = shift @a ) { print ",",$next } print "\n"; $first = shift @b ; print "b $#b shift ",$first,"->"; while ( $next = shift @b ) { print ",",$next } print "\n"; $first = pop @x ; print "x $#x pop ",$first,"->"; while ( $next = pop @x ) { print ",",$next } print "\n"; $first = pop @y ; print "y $#y pop ",$first,"->"; while ( $next = pop @y ) { print ",",$next } print "\n"; $first = pop @r ; print "r $#r pop ",$first,"->"; while ( $next = pop @r ) { print ",",$next } print "\n"; Gives --- >>>>> See line starting x $ perl test.pl a 2 shift 0->,1,2,3 b 2 shift 1->,2,3,4 x 2 pop 3->,2,1 y 2 pop 4->,3,2,1 r 2 pop 0->,1,2,3
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: pop and shift not reversible
by hippo (Archbishop) on Mar 20, 2020 at 10:59 UTC | |
|
Re: pop and shift not reversible
by BillKSmith (Monsignor) on Mar 20, 2020 at 14:42 UTC | |
|
Re: pop and shift not reversible
by talexb (Chancellor) on Mar 20, 2020 at 13:39 UTC | |
|
Re: pop and shift not reversible
by Anonymous Monk on Mar 20, 2020 at 14:05 UTC | |
|
Re: pop and shift not reversible ( while @array )
by Anonymous Monk on Mar 20, 2020 at 12:19 UTC | |
by gannett (Novice) on Mar 20, 2020 at 17:53 UTC |