Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

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

by Anonymous Monk
on Apr 01, 2005 at 17:34 UTC ( [id://444243]=note: print w/replies, xml ) Need Help??


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

splice() is fun. (Pls. to pardon ugly.)
#!/usr/bin/perl @a=("a","b","c","b","a"); $targ="b"; $ins="d"; THINGY: foreach(@a) { $_ =~ $targ && do { splice(@a,$i,1,($_, $ins)); last THINGY }; $i++; }; print join ", ", @a; print "\n"
Output:
a, b, d, c, b, a
It's not entirely cool; it does take an iterator, which I accept is fairly cheesy, but it does the job in a single foreach() that probably won't even make it to the end of the array.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2024-04-25 09:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found