Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: range comparison in given

by kcott (Archbishop)
on Jul 11, 2013 at 07:53 UTC ( [id://1043640]=note: print w/replies, xml ) Need Help??


in reply to range comparison in given

G'day mrguy123,

"Solved -thanks for the help. Am now trying to discover how "safe" using given/when is (as of Perl 5.18, given/when has been marked experimental and issues warnings because it may undergo major changes in a future version of Perl)"

You can avoid the (experimental) given/when/.../default construct by using a (non-experimental) for/if/elsif/.../else construct. Here's an example for your specific range comparison:

$ perl -Mstrict -Mwarnings -E ' my $re_2_5 = qr{^@{[join "|", 2 .. 5]}$}; my $re_6_10 = qr{^@{[join "|", 6 .. 10]}$}; for my $x (4 .. 7, 11) { for ($x) { if (/$re_2_5/) { say "$_ in 2-5 range" } elsif (/$re_6_10/) { say "$_ in 6-10 range" } else { say "$_ not in range" } } } ' 4 in 2-5 range 5 in 2-5 range 6 in 6-10 range 7 in 6-10 range 11 not in range

There's lots of other ways to achieve this. Here's one using nested ternary operators:

$ perl -Mstrict -Mwarnings -E ' my $re_2_5 = qr{^@{[join "|", 2 .. 5]}$}; my $re_6_10 = qr{^@{[join "|", 6 .. 10]}$}; for my $x (4 .. 7, 11) { for ($x) { say /$re_2_5/ ? "$_ in 2-5 range" : /$re_6_10/ ? "$_ in 6-10 range" : "$_ not in range" } } ' 4 in 2-5 range 5 in 2-5 range 6 in 6-10 range 7 in 6-10 range 11 not in range

See also perlsyn - Basic BLOCKs which has other alternatives.

-- Ken

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (7)
As of 2024-04-23 13:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found