[Omaha.pm] map {} instead of $i

Andy Lester andy at petdance.com
Thu Feb 11 12:02:59 PST 2010


On Feb 11, 2010, at 1:56 PM, Jay Hannah wrote:

> foreach (my $i=0; $i < scalar(@a); $i++) {
>   $a[$i] = -1 unless (defined $a[$i]);
> }
>
>
> AFTER:
>
> @a = map { defined $_ ? $_ : -1 } @a;


Yes, that's what map is for.  But you're using indexing you don't  
need.  In for() loops, $_ is an alias to the real element.

for ( @a ) {
     $_ = -1 unless defined($_);
}

That way you're doing it in place, instead of creating a new array and  
then replacing the original.

http://perl101.org/flow-control.html

xoxo,
Andy


--
Andy Lester => andy at petdance.com => www.theworkinggeek.com => AIM:petdance






More information about the Omaha-pm mailing list