Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^2: my 'if' condition doesn't work, why?

by perltux (Monk)
on Nov 11, 2014 at 22:00 UTC ( [id://1106899]=note: print w/replies, xml ) Need Help??


in reply to Re: my 'if' condition doesn't work, why?
in thread my 'if' condition doesn't work, why?

This looks like the 'nicest' (from a code readability and compactness point of view) solution to me, shame that it's not standard Perl but instead requires an extra module.

So I have chosen to use
if ($n==40 || $n==47 || $n==76) {
which works fine too (regardless whether I use 'or' or '||').

Many thanks to all who replied for your help.

Replies are listed 'Best First'.
Re^3: my 'if' condition doesn't work, why?
by Athanasius (Archbishop) on Nov 12, 2014 at 07:36 UTC
    shame that it's not standard Perl but instead requires an extra module

    Well, you can get a similar result using List::Util, which is a core module:

    #! perl use strict; use warnings; use List::Util 'any'; for my $n (0 .. 267) { print "$n\n" if any { $n == $_ } (40, 47, 76); }

    Update: Fixed off-by-one error in the for loop range, thanks to AnomalousMonk.

    Output:

    17:34 >perl 1074_SoPW.pl 40 47 76 17:34 >

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re^3: my 'if' condition doesn't work, why?
by tobyink (Canon) on Nov 17, 2014 at 11:29 UTC

    "shame that it's not standard Perl but instead requires an extra module"

    Well, there does exist something similar in core Perl since 5.10: the smart match operator! Example:

    if ($n ~~ [40, 47, 76]) { ...; }

    However, smart match acts pretty weird in some cases (not the above case), so it is not usually a great idea to use it.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1106899]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (5)
As of 2024-04-25 13:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found