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 ()?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With