Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Array Splicing: Need Help!

by Alberta226 (Initiate)
on May 26, 2005 at 08:44 UTC ( #460571=perlquestion: print w/replies, xml ) Need Help??
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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://460571]
Approved by ghenry
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2018-07-19 00:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?















    Results (398 votes). Check out past polls.

    Notices?