Although Abigail-II already told you, he was perhaps not very clear about the reason why your code was not working as you expected.

We read in the docs about a foreach loop:

The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn.
and :
In other words, the foreach loop index variable is an implicit alias for each item in the list that you're looping over..
So there is no need to stuff your $item variable with a pop-ed value from the @listoitems array. You will not only overwrite what was already in $item, but you will at the same time replace the array-element to which $item was aliased to with the value just pop-ed from the array and you will have shortened the array by one (which is an unescapable side-effect of pop.

The docs warn you about changing the length of the array you are working with:

If any part of LIST is an array, foreach will get very confused if you add or remove elements within the loop body, for example with splice. So don't do that.

Try this little program and you will see how your script affects the array:

use Data::Dumper; @array = 0 ... 9; foreach $item (@array) { print ++$i . " through the loop\n"; $item = pop @array; print Dumper(\@array); }

CountZero

"If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law


In reply to Re: pop an array by CountZero
in thread pop an array by JayBee

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.