Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

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 (Parson) 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
[choroba]: I've moved away from nvidia
[davido]: I have nvidia (1050ti) in one system at home. My work laptop came with a radeon/amd video system that is no longer supported by debian/ubuntu. So that being the case I'm in the "prefer nvidia even if proprietary" camp
[davido]: Especially since the laptop is only a couple years old.

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (13)
As of 2017-05-26 14:24 GMT
Find Nodes?
    Voting Booth?