Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

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

by ambs (Pilgrim)
on Mar 31, 2005 at 18:40 UTC ( #443924=note: print w/replies, xml ) Need Help??


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

Say, you have "a,b,c,d,e" and want a "f" after "c":
@array = map { $_ eq "c" ? ("c","f") : $_ } @array
but this would insert "f" for each "c" you have.

Alberto Simões

Replies are listed 'Best First'.
Re^2: Inserting an element into an array after a certain element
by RazorbladeBidet (Friar) on Mar 31, 2005 at 18:58 UTC
    You could easily fix that by adding a counter:
    @array = map { $_ eq "c" && !$found++ ? ("c","f") : $_ } @array
    (as a sub)
    sub insert_after_first { my $arr_ref = shift; my $to_insert = shift; my $insert_after_me = shift; my $found = 0; map { $_ eq $insert_after_me && !$found++ ? ( $insert_after_me, $to +_insert ) : $_ } @$arr_ref; }
    --------------
    "But what of all those sweet words you spoke in private?"
    "Oh that's just what we call pillow talk, baby, that's all."
Re^2: Inserting an element into an array after a certain element
by ikegami (Pope) on Mar 31, 2005 at 19:07 UTC

    Ajusted to only do it once:

    my $first = 1; @array = map { if ($first && $_ eq "c") { $first = 0; ($_, "x") } else { $_ } } @array;

    hum, ugly. How about:

    my $first = 1; @array = map { my @a = $_; push(@a, "x") if ($first && $_ eq "c"); $first ||= @a-1; @a } @array

    Nope, still ugly. Well, you could always do:

    foreach (0..$#array) { if ($array[$_] eq "c") { splice(@array, $_+1, 0, "x"); last; } }
Re^2: Inserting an element into an array after a certain element
by nimdokk (Vicar) on Apr 01, 2005 at 19:10 UTC
    Actually, I think this is along the lines of what I'm looking to do with something I'm working on.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2020-03-30 16:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    To "Disagree to disagree" means to:









    Results (175 votes). Check out past polls.

    Notices?