Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, Just out of curiosity (and to make my code a bit nicer) is there a way to pop e.g. 5 elements of the end of an array in one line? Rather than typing:
pop @array; pop @array; pop @array; pop @array; pop @array;

Replies are listed 'Best First'.
Re: using pop a lot
by liz (Monsignor) on Oct 10, 2003 at 12:05 UTC
    splice():
    splice @array,-5,5,();
    A directly executable example:
    $ perl -e '@a=(1,2,3,4,5);splice @a,-2,2,();print "@a\n"' 1 2 3

    Liz

      Or shorter:
      splice @array => -5;

      Abigail

        Actually, it can still get shorter without splice():
        $#array -= 5;

        Liz

        Update:
        Although I would probably use Abigail-II's way, but without the fat comma:

        splice @a,-5;
Re: using pop a lot
by Aragorn (Curate) on Oct 10, 2003 at 11:40 UTC
Re: using pop a lot
by BrowserUk (Patriarch) on Oct 10, 2003 at 12:26 UTC

    Just for variety...

    perl -le"$,=' '; @a=(1..10); print 'start with ', scalar @a, ' delete 5 [', delete @a[-5..-1], '] leaves ', scalar @a" start with 10 delete 5 [ 6 7 8 9 10 ] leaves 5

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail

Re: using pop a lot
by hawtin (Prior) on Oct 10, 2003 at 12:07 UTC

    Why do you want to do this? If you want to remove 5 elements without calling pop 5 times you can:

    splice @array,$#array-4,5;

    (With the usual caveat about $[)

    Update: Typical, wait 20 minutes for an answer then two come along at once

    If you want to grab 5 items to do something with them you can also do:

    my @poped = splice @array,$#array-4,5; my $val0 = $poped[0];
Re: using pop a lot
by delirium (Chaplain) on Oct 11, 2003 at 11:45 UTC
    Personally, I wouldn't want to miss the opportunity to say "pop pop pop pop pop" somewhere in my code....

    eval $_.' @array' for qw(pop pop pop pop pop);

      eval join(';', map $_.'@array', /pop/g) for q{low heat: pop, pop.. pop-pop, pop-pop.. pop! pop! pop, pop, pop. +.}, q{turning up the heat: fffffffpop!! poppoppoppoppop!!!};
      %-D

      Makeshifts last the longest.

        This is one of the few nodes in the Monastery that create an auditory illusion for me.

        Or in other words: I can hear them poppin'! ;-)

        Liz