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

Basically, I would like to add an element to the middle of an array. I know there is code for it because i've seen it (probably used it before). I think that it goes something like:
$newelement = 54; for $i (5..($last + 1)) { $temp = $a[$i]; $a[$i] = $newelement; $newelement = $a[($i+1)]; }
So I want to add the element and expand the array by one. Is this close?

update (broquaint): title change (was adding to the middle of a array)

Replies are listed 'Best First'.
Re: adding to the middle of a array
by mirod (Canon) on Feb 13, 2003 at 09:52 UTC

    You can use splice:

    splice( @a, 5, 0, $newelement)

    This will replace the fragment of list at index 5, with a length of 0, with the rest of the arguments, here a single element. See perldoc -f splice for more info.

Re: adding to the middle of a array
by TheHobbit (Pilgrim) on Feb 13, 2003 at 09:56 UTC

    Hi,
    Obviously, the one you gave is 'a way' to do it... but there is more than one. The following is the one I use:

    my @a = (1,2,3,4,5,6,7,8,9); my $pos = 3; my $new_elem = 100; $" = ", "; print "Before: (@a)\n"; @a = (@a[0..$pos-1],$new_elem,@a[$pos..$#a]); print "After: (@a)\n";

    I'm sorry that I haven't the time now to benchmark these solutions...

    I hope this serves to help you.

    Cheers


    Leo TheHobbit
      Lesson to be learned from this: Use the builtins.

      You method will copy the entire @a array back and forth, while the builtin splice will do as little work as possible (and probably will add to the array by shuffling around with pointers instead of copying the contents).

      A simple benchmark:

      use Benchmark "timethese"; my @c = (1,2,3,4,5,6,7,8,9); my @s = (1,2,3,4,5,6,7,8,9); my $pos = 3; my $new_elem = 100; timethese(5000, { COPY => sub {@c = (@c[0..$pos-1],$new_elem,@c[$pos..$#c])}, SPLICE=> sub {splice (@s, $pos, 0, $new_elem)}, }); print "\nAfter iters: size(\@copy): ", scalar @c, " and size(\@splice) +: ", scalar(@s), "\n";
      will show that:
      Benchmark: timing 5000 iterations of COPY, SPLICE...
            COPY: 12 wallclock secs (11.88 usr +  0.00 sys = 11.88 CPU) @ 420.76/s (n=5000)
          SPLICE:  0 wallclock secs ( 0.05 usr +  0.00 sys =  0.05 CPU) @ 100000.00/s (n=5000)
                  (warning: too few iterations for a reliable count)
      
      After iters: size(@copy): 5009 and size(@splice): 5009
      
      The COPY times get worse and worse, while SPLICE has to get up to 50000 iterations before it takes even 6 wallclock seconds.

        Hi,
        I take the point, and start to read over the camel book as a penance for not having seen how my solution implied a hidden copy...

        Well, ok, reading the Camel Book is not much of a penance, quite the contrary, but WTF... :)

        Cheers


        Leo TheHobbit
        It's very interesting - when I try to increase the iterations to 50000, I see the SPLICE performance drops significant now - Benchmark: timing 50000 iterations of SPLICE... SPLICE: 4 wallclock secs ( 4.28 usr + 0.00 sys = 4.28 CPU) @ 11679.51/s (n=50000) Wonder why it's getting slower...? Daniel