### Re: range comparison in given

by kcott (Chancellor)
 on Jul 11, 2013 at 07:53 UTC ( #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

Create A New User
Node Status?
node history
Node Type: note [id://1043640]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2018-04-21 10:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My travels bear the most uncanny semblance to ...

Results (81 votes). Check out past polls.

Notices?