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

hello, do any of you care to tell me the easiest way to insert an array element in betwene two other elements? like if you have (a,b,c,d) to insert '1', so that you have (a,b,1,c,d) (thats just an example)? thank you

Replies are listed 'Best First'.
Re: insertion of array element
by wog (Curate) on Jun 03, 2001 at 05:24 UTC
    my @a = qw(a b c d); # 0 1 2 3 print "@a\n"; # a b c d splice @a, 2, 0, qw(ba bb bc); print "@a\n"; # a b ba bb bc c d

    See what perlfunc has to say about splice.

      Good post. If you wanted to get it in the middle of an array more that 4 indexes then you could make a slight adjustment to it to be more versatile.

      my @a = (a..g); print "@a\n"; splice @a, ($#a+1)/2, 0, (1..5); print "@a\n";


      Tiptoeing up to a Perl hacker.
      Dave AKA damian

        I keep seeing $#list + 1 in code posted to perlmonks. Remember that this is the same thing as @list in a scalar context.

        Henceforth, I shall wage a jihad against the former expression :)

           MeowChow                                   
                       s aamecha.s a..a\u$&owag.print
(bbfu) (splice) Re: insertion of array element
by bbfu (Curate) on Jun 03, 2001 at 05:24 UTC

    splice

    Update: Okay, wog. You beat me. :-p And your answer is more informative, too. Shucks.

    bbfu
    Seasons don't fear The Reaper.
    Nor do the wind, the sun, and the rain.
    We can be like they are.