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 MacBookPro
use 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

In reply to pop and shift not reversible by gannett

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.