http://www.perlmonks.org?node_id=460571

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

Hiya PerlMonks! I have this code:
#!/usr/bin/perl use warnings; use strict; ############################################################# # Array splicing # Removing elements then returning more than one element at a time ############################################################# my @colors = ("red", "blue", "orange", "purple", "pink", "white"); splice(@colors, 0, 2); print @colors;
It is suppose to remove the first three sets of information from the list leaving purple, pink and white. Instead I get oranglepurplepinkwhite Any ideas?

Replies are listed 'Best First'.
Re: Array Splicing: Need Help!
by Hena (Friar) on May 26, 2005 at 08:48 UTC
    The third argument is lenght (not last to be removed as I assume you are thinking). As you set lenght into 2, so it removes two elements.
      as can easily be discovered by typing
      perldoc -f splice splice ARRAY,OFFSET,LENGTH Removes the elements designated by OFFSET and LENGTH from an array, and replaces them with the elements of LIST, if any.
      ---
      my name's not Keith, and I'm not reasonable.
Re: Array Splicing: Need Help!
by monkfan (Curate) on May 26, 2005 at 09:32 UTC
    Or try "array slice"
    $ perl -e ' my @colors = qw(red blue orange purple pink white); @colors = @colors[3..$#colors]; print join (" ", @colors),"\n";'
    prints:
    purple pink white
    Update: Check perldata for more detail explanation about slice.

    Regards,
    Edward
      Cool! Does that mean we can always replace "splice" with "slicing"?
      Is there any case where only "splice" works but not slicing?

        Splicing modifies the array. Slicing returns a list without modifying the original data structure (whether it's a hash, an array, or a list).

Re: Array Splicing: Need Help!
by rupesh (Hermit) on May 26, 2005 at 09:25 UTC

    C:\>perl my @colors = ("red", "blue", "orange", "purple", "pink", "white"); splice(@colors, 0, 3); print "@colors"; ^D purple pink white C:\>

    Cheers,
    Rupesh.