For this to work, the map block must return an empty list of unwanted elements. Although the code was rewritten using grep ,
my @squares = map { $_**2 } grep { $_ > 5 } @numbers;
it loses a lot of elegance.
If we do not specify the return value of else , if , apparently, implicitly passes a false value:
say $_+0 for map{ if($_>5){$_**2} } 3..7;
which is useless for our purpose.
But we can always write a filtering map that returns the value of our block, or an empty list if it was false:
sub mapgrep (&@) { my $cb = shift; map { local $_ = $_; $cb->($_) || () } @_; } my @squares = mapgrep { $_**2 if $_ > 5 } @numbers;
However, this depends on the side effect that the conditional returns the value of the condition, unless this condition is otherwise handled. I do not see where this is explicitly documented.
(Note: Perl does not have the then keyword).
source share