in reply to Re: if block inside map
in thread if block inside map
Just to elaborate a little. You can also leave off the else branch, in which case map would return the empty string (not sure why not undef) when the if-condition isn't true:
my @x = map { if ($_ > 0) { $_*2 } } (-2 .. 2); use Data::Dumper; print Dumper \@x; __END__ $VAR1 = [ '', '', '', 2, 4 ];
When you don't want to return anything in those cases, you can use the empty list ():
my @x = map { if ($_ > 0) { $_*2 } else { () } } (-2 .. 2); # or: my @x = map { $_ > 0 ? $_*2 : () } (-2 .. 2); use Data::Dumper; print Dumper \@x; __END__ $VAR1 = [ 2, 4 ];
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: if block inside map
by AnomalousMonk (Archbishop) on Nov 11, 2011 at 21:14 UTC | |
by Eliya (Vicar) on Nov 11, 2011 at 23:57 UTC |