Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

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

by tall_man (Parson)
on Apr 01, 2005 at 00:52 UTC ( [id://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); }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (8)
As of 2024-04-19 11:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found