in reply to Inserting into an array while stepping through it

Maybe a good use for the function map. Layman's terms: It applies a sub to each item of a list, and it returns a list of all the sub results. Okay, a better example: You have a list with numbers, you want a list of each number, times 3.
my @list = ( 5, 11, 7); my @timesthree = map { $_ *= 3 } (@list);
or if you only want to operate on multiples of five:
my @timesthree_onlyfives = map { $_ *= 3 if ($_ % 5 == 0) } (@list);
BUT, you will get a list of one item! so you want:
my @all_timesthree_onlyfives = map { if ($_ % 5 ==0) { $_ *= 5; } else { return $_; } } (@list);
But that could be done better.

Hope I've described it well, and HTH!

mhoward - at - hattmoward.org

Replies are listed 'Best First'.
Re: Re: Inserting into an array while stepping through it
by sauoq (Abbot) on Jun 13, 2003 at 02:43 UTC

    Well, map() is a good alternate solution (though it wouldn't be doing the modification in place exactly.) But, you didn't show how to use it in the way he wants to...

    @list = map { $_ eq 'condition' ? my_sub( $_ ) : $_ } @list;
    and yes, that'll work when my_sub() returns a list too.

    -sauoq
    "My two cents aren't worth a dime.";
    
      Thanks for the code -- I just wanted to include an explanation for the code I posted, instead of a one-liner and some code. Anonymous Monk sure posts a lot of questions, and I want to help him learn. ;) Besides, everyone knows that using map scores you extra Perl Points(tm)!!

      mhoward - at - hattmoward.org