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

Hello,
How can I insert elements anywhere inside the array? If
@fred = ( "a", "b", "c" );
and I want to insert "hello" in index 2 i.e. between "b" and "c", how can I do that?

Thank you in advance.

Replies are listed 'Best First'.
Re: inserting elements in an array
by osunderdog (Deacon) on Feb 02, 2005 at 23:41 UTC

    Look at perldoc -f splice

    Here is an example

    sub strict; my @a1 = qw|a b c d e f|; splice @a1, 3, 0, 'x', 'y', 'z'; print join(',', @a1); print "\n";

    Returns:

    a,b,c,x,y,z,d,e,f

    "Look, Shiny Things!" is not a better business strategy than compatibility and reuse.

      I learned about splice() while examining the Games::Card module. I did not need the full power of that module but did want the "pick a card, any card" functionality.

      --- The harder I work, the luckier I get.

        Right, but splice is a core part of the Perl language, not an external module nor some function of an external module. It's described in perlfunc.


        Dave

Re: inserting elements in an array
by brian_d_foy (Abbot) on Feb 03, 2005 at 01:14 UTC

    This does what you ask:

    #!/usr/bin/perl my @fred = ( "a", "b", "c" ); splice @fred, 2, 0, "hello"; print "@fred\n";

    splice() takes four arguments: the array, the position to start at, the length of the sub-list to replace, and the list to replace it with. That sub-list length is the tricky part: make it 0 to insert things into the array. Any ordinal number "overwrites" that many elements in the array. For instance, make the third argument 1 and you'll see the "c" disappear since it's replaced.

    --
    brian d foy <bdfoy@cpan.org>
Re: inserting elements in an array
by ambrus (Abbot) on Feb 03, 2005 at 20:13 UTC

    There are two easy ways to do this. One is splice, as others have shown:

    splice @fred, 2, 0, "hello";
    the other is
    @fred[2 .. @fred] = ("hello", @fred[2 .. @fred - 1]);
    which has the advantage that you don't have to remember the way splice interprets its arguments.

    Update: D'oh, there's one more way I've forgot, although I've done something similar in Re: finding top 10 largest files:

    @fred = (@fred[0 .. 2 - 1], "hello", @fred[2 .. @fred - 1]);
      Huh, I've always thought that splice has pretty intuitive arguments. Would you have expected some different order?