[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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




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@petdance.com => www.theworkinggeek.com => AIM:petdance