in reply to Re: if block inside map
in thread if block inside map

ouh man, you made my day with this. Specially with ternary operator

Replies are listed 'Best First'.
Re^3: if block inside map
by AnomalousMonk (Archbishop) on Dec 08, 2015 at 16:59 UTC

    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:  <%-{-{-{-<