Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

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

by tall_man (Parson)
on Apr 01, 2005 at 00:52 UTC ( #444037=note: print w/ replies, xml ) Need Help??


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


Comment on Re: Inserting an element into an array after a certain element
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://444037]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (8)
As of 2014-07-28 09:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (194 votes), past polls