in reply to Inserting an element into an array after a certain element

A variation using index (you didn't say it had to be efficient!)

sub insert_after_first { my ( $a_ref, $afterthis, $insertme ) = @_; my $pos = index( join( '', @$a_ref ), $afterthis ); splice( @$a_ref, $pos+1, 0, $insertme ) if $pos >= 0; }

Update: As tall_man mentioned, this only works when the elements of the array are single characters, because the offset for splice represents the number of chars from the beginning of the string/array (rather than the number of individual array elements). Thanks for pointing it out. (I still thought it was a neat idea for the sample data, though!)

Replies are listed 'Best First'.
Re^2: Inserting an element into an array after a certain element
by tall_man (Parson) on Apr 01, 2005 at 15:06 UTC
    This doesn't work if you try it on a non-toy example where the array contains more than single-letter keys.