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

For some reason I can't wrap my brain around splice today...

Given an array, say @a = ('a','b','c'), I want to insert, say, 'foo' into the third position, ending up with @a being ('a','b','foo','c'), but for some reason, my attempts at deciphering perldoc -f splice have failed me. A little help?

Replies are listed 'Best First'.
Re: A silly splicing question...
by marius (Hermit) on Jan 19, 2001 at 05:11 UTC
    From the holy book of the camel:
    splice ARRAY, OFFSET, LENGTH, LIST
    splice ARRAY, OFFSET, LENGTH
    splice ARRAY, OFFSET
    This function removes the elements designated by OFFSET and
    LENGTH from an array, and replaces them with the elements
    of LIST, if any. The function returns the elements removed
    from the array. The array grows or shrinks as necessary. If
    LENGTH is omitted, the function removes everything from
    OFFSET onward.
    I'm not sure (not too familiar with splice) if you could set a length of 0, and do:
    splice @a, 2, 0, 'foo'
    Any takers care to deny or confirm this?

    -marius

    Update:redcloud, and a few others have either posted or CB'd me to let me know it works. woohoo! =]
      Confirmed. Setting LENGTH to 0 will insert LIST without removing any elements from ARRAY.

      Yepyep, that was the ticket. For some reason it hadn't occured to me to set length to zero (despite the docs blatantly pointing that out). myocom-- for stupidity. :-)

      Thanks!

Re: A silly splicing question...
by Maclir (Curate) on Jan 19, 2001 at 05:13 UTC
    Hmmm - this is almost a "second coffee of the day" question. Looking at the doco for splice, you could do:
    @last_bit = splice(@a, 2, , 'foo');
    to remove the 'c' and replace it with 'foo'. Then a
    @a .= @last_bit;
    to stick the removed things back on the end.

    I am sure there is a way to combine the two operations.

    Updated: redcloud had it - set length to 0 and it automagically happens. Sigh. Where is that coffee?