Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

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

by DrWhy (Chaplain)
on Apr 01, 2005 at 15:16 UTC ( [id://444213]=note: print w/replies, xml ) Need Help??


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

Okay, I gotta throw my hat in the ring here...

sub insert_after_first { my ($ndx, $arr, $elt, $ins) = (0, @_); $ndx > @$arr and return while $arr->[$ndx++] ne $elt; splice @$arr, $ndx, 0, $ins; }

Update: Here's a version that is a little more efficient, removing one boolean comparison from the loop.

sub insert_after_first { my ($ndx, $arr, $elt, $ins) = (0, @_); $arr->[$ndx++] eq $elt and last for 0 .. @$arr; splice @$arr, $ndx, 0, $ins if $ndx <= @$arr; }

--DrWhy

"If God had meant for us to think for ourselves he would have given us brains. Oh, wait..."

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2024-04-16 10:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found