Perl Monk, Perl Meditation PerlMonks

### if block inside map

by mhearse (Chaplain)
 on Nov 11, 2011 at 16:15 UTC Need Help??
mhearse has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to figure out how to put an if block inside a map. Can someone give me an example?

Replies are listed 'Best First'.
Re: if block inside map
by choroba (Bishop) on Nov 11, 2011 at 16:23 UTC
```@x = map { if (\$_ > 1) { 1 } } (-5 .. 5)
[download]```
But trying to read your mind, I suppose you need rather
```@x = map { if (\$_ > 1) { 1 } else { 0 } } (-5 .. 5)
[download]```
which can be also written with the ternary operator:
```@x = map { \$_ > 1 ? 1 : 0 } (-5 .. 5)
[download]```

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
];
[download]```

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
];
[download]```
ouh man, you made my day with this. Specially with ternary operator

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]
[download]```
• 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]
[download]```
(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:  <%-{-{-{-<

Re: if block inside map
by Corion (Pope) on Nov 11, 2011 at 16:22 UTC

Have you looked at map? What parts of it do you have problems with? What else have you tried, and how did it fail?

Log In?
 Username: Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://937607]
Approved by Corion
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2017-10-21 13:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My fridge is mostly full of:

Results (270 votes). Check out past polls.

Notices?