in reply to Working Through An Array In Chunks

Use splice! It not only chops out the section of the array, it returns what what was removed, and handles all the degenerate cases (when the array has fewer than 20 elements) as well.
my @array = (1 .. 55); while ( my @chunk = splice @array, 0, 20 ) { print "<@chunk>\n"; }

blokhead

Replies are listed 'Best First'.
Re^2: Working Through An Array In Chunks
by Cody Pendant (Prior) on Dec 06, 2004 at 22:43 UTC
    Thanks, that was the kind of answer I really wanted. I always forget "splice" for some reason, or get it mixed up with "slice". Why is it called "splice"? The literal meaning of that word is something more like "join", surely? Maybe it's a kind of combination of "slice" and "pop"?


    ($_='kkvvttuubbooppuuiiffssqqffssmmiibbddllffss')
    =~y~b-v~a-z~s; print

      "splice" makes perfect sense when you're extracting middle elements from an array and thus splicing together the leading and trailing elements.

      It makes, um, a little less sense when you're using it just to remove elements from the head or tail (to be clear, I'm speaking only of the command's name, not of its appropriateness for the task.)

      Though you could argue, say, that you're splicing together array position 0 and the middle of the array when you're removing elements from the head...

        I get your point.

        Does the word in this context originate with Perl, or is it used in other languages as well? I want to write to Larry and ask.



        ($_='kkvvttuubbooppuuiiffssqqffssmmiibbddllffss')
        =~y~b-v~a-z~s; print