Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping: Can we use something in lieu of the conditional operator

Tags:

perl

So, I understand what the following code does and why it works, but it seems like there should be a different way to do this:

my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers;

Is there a way that we can essentially say:

my @squares = map { if ($_ > 5) then ($_ * $_) } @numbers;

Or do we have to have "rule" for every entry, ie else return ()?

like image 706
Steve P. Avatar asked Dec 21 '22 05:12

Steve P.


1 Answers

amon gave you lots of info, but didn't actually answer the question. The equivalent of

map { $_ > 5 ? ($_ * $_) : () }

using if instead of the conditional operator is

map { if ($_ > 5) { $_ * $_ } else { () } }

It's impossible for the map expression not to return a value. It returns the last expression evaluated. If you remove the else clause, that expression is the comparison, so it would similar to if you did

map { if ($_ > 5) { $_ * $_ } else { $_ > 5 } }

though $_ > 5 only gets executed once, so I guess it's closer to

map { ($_ > 5) && ($_ * $_) }

So yes, you do have to have a rule for every entry, in the sense that it's impossible not to.

like image 60
ikegami Avatar answered Apr 06 '23 00:04

ikegami