Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
Don't ask to ask, just ask
 
PerlMonks  

Re: Inserting an element into an array after a certain element

by tall_man (Parson)
on Mar 31, 2005 at 19:52 UTC ( [id://444037]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


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); }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://444037]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.