in reply to Inserting an element into an array after a certain element
I haven't seen a solution with "grep" yet, which feels natural to me for this problem:
sub insert_after_first { my ($arr, $find, $insert) = @_; my $found = 0; my ($pos) = grep { $arr->[$_] eq $find and !$found++ } 0..$#$arr; splice @$arr, $pos+1, 0, $insert if $found; }
Update: A shorter, slightly neater variant:
sub insert_after_first { my ($arr, $find, $insert) = @_; my ($pos) = grep { $arr->[$_] eq $find } 0..$#$arr; splice @$arr, $pos+1, 0, $insert if defined($pos); }
|
---|
In Section
Seekers of Perl Wisdom