Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

if block inside map

by mhearse (Hermit)
on Nov 11, 2011 at 16:15 UTC ( #937607=perlquestion: print w/ replies, xml ) 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?

Comment on if block inside map
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?

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

      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 ];

      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 ];

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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (10)
As of 2014-10-24 12:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (131 votes), past polls