@x = map { if ($_ > 1) { 1 } } (-5 .. 5)
But trying to read your mind, I suppose you need rather
@x = map { if ($_ > 1) { 1 } else { 0 } } (-5 .. 5)
which can be also written with the ternary operator:
@x = map { $_ > 1 ? 1 : 0 } (-5 .. 5)
| [reply] [d/l] [select] |
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
];
| [reply] [d/l] [select] |
| [reply] |
ouh man, you made my day with this. Specially with ternary operator
| [reply] |
Other ways:
-
If you can use empty strings instead of zeros in the output list (i.e., you're not doing arithmetic with the elements of the output),
then either map { $_ > 0 } or just map $_ > 0, (note the terminating comma) will do the trick:
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le
"my @x = map $_ > 1, -3 .. 3;
dd \@x;
"
["", "", "", "", "", 1, 1]
-
If you gotta have 0s, || or or will do:
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le
"my @x = map { $_ > 1 or 0 } -3 .. 3;
dd \@x;
"
[0, 0, 0, 0, 0, 1, 1]
(Note that map $_ > 1 || 0, -3 .. 3 would also work, but map $_ > 1 or 0, -3 .. 3 will not. Can you say why? This is one reason why some Best Practices recommend avoiding the map EXPR, LIST form of map.)
-
And of course, there are other ways...
Give a man a fish: <%-{-{-{-<
| [reply] [d/l] [select] |
Have you looked at map? What parts of it do you have problems with? What else have you tried, and how did it fail?
| [reply] |