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

Updated to address Roy Johnson's concerns below

sub insertAfter{ use List::Util qw[ first ]; my( $aref, $before, $insert ) = @_; my $first = first{ $aref->[ $_ ] eq $before } 0 .. $#$aref ; return unless defined $first; splice @{ $aref }, ++$first, 0, $insert; }

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco.
Rule 1 has a caveat! -- Who broke the cabal?

Replies are listed 'Best First'.
Re^2: Inserting an element into an array after a certain element
by Roy Johnson (Monsignor) on Mar 31, 2005 at 19:11 UTC
    If the $before isn't found, though, it inserts $insert after the first element.

    Caution: Contents may have been coded under pressure.