Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

delete n elements of an array

by Anonymous Monk
on Nov 25, 2012 at 12:58 UTC ( #1005483=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I have an array which contains 20 elements, I need to delete the first 15. Only last 5 is needed. Can any Monks suggest me a simple way. Thanks.

Replies are listed 'Best First'.
Re: delete n elements of an array
by jwkrahn (Monsignor) on Nov 25, 2012 at 13:03 UTC
    $ perl -le' my @array = 1 .. 20; print "@array"; splice @array, 0, 15; print "@array"; ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 16 17 18 19 20

      Thanks monk, 1 more doubt. what should I do if I want to Pop 15 elements, ie, from last I want to cut. Thanks in advance.

Re: delete n elements of an array
by space_monk (Chaplain) on Nov 25, 2012 at 16:19 UTC
    As jwkrahn has noted splice is the core method for adding and removing elements to/from an array. Read the documentation for the function as it does everything you seem to want to do.
    A Monk aims to give answers to those who have none, and to learn from those who know more.
Re: delete n elements of an array
by karlgoethebier (Prior) on Nov 26, 2012 at 08:52 UTC

    A variation:

    #!c:/perl/bin/perl.exe use autobox::Core; use strict; use warnings; my $list = 1->to(20); $list->join(" ")->say; $list = $list->tail(5); $list->join(" ")->say; __END__ > 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 16 17 18 19 20

    Regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1005483]
Approved by Athanasius
[erix]: what's the offending signature?
[Discipulus]: 'give man a fish erix it sonds like a push towards omosexuality.. ;=)
[Discipulus]: see Re: from txt file to array erix
[erix]: yeah, I ask for the text (I don't see signatures)
[Discipulus]: dear brother karl has "Furthermore I consider that Donald Trump must be impeached as soon as possible" in his sig
[erix]: ah, thanks Discipulus
[1nickt]: erix perhaps you could kindly point out your technique to roho and everyone will be happy.

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (11)
As of 2017-06-22 12:29 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (519 votes). Check out past polls.