Is there such a thing? The equivalent of a <= expr <= b
, or in SQL parlance expr BETWEEN a AND b
, where expr
is evaluated only once? Or is asking for this just getting silly?
views:
224answers:
5
A:
I think this is your only bet.
$x = expr;
if ($a < $x && $x < $b) {
# stuff
}
Tenner
2009-11-06 21:43:58
Tempted to -1 for saying "only one way to do it"
mobrule
2009-11-06 21:49:14
So far, this is the only answer that's correct for things other than integers.
jrockway
2009-11-07 13:24:44
+1
A:
I do not think they correspond exactly, but take a look at the Range Operators.
Sinan Ünür
2009-11-06 21:44:23
+4
A:
you could use Range operator
+ smart macthing
:
if($expr ~~ [$a..$b])
najmeddine
2009-11-06 22:03:08
+12
A:
There are a variety of ways to do that in Perl.
if( $a < $x and $x < $b ){ ... }
... if $a < $x and $x < $b;
use 5.10.1;
if( $x ~~ [$a..$b] ){ ... }
given( $x ){
when( [$a..$b] ){ ... }
}
use 5.11.0; # development branch
given( $x ){
... when [$a..$b];
}
Brad Gilbert
2009-11-06 22:14:50
Does this work the way you want? I only have 5.10.0 available right now, but the 5.10.1 and 5.11.x manuals don't mention any change for smart matching range operators, and the SCALAR ~~ ARRAY semantics will only work out if you have integers. Now if this were Perl 6, where ranges are their own type...
hobbs
2009-11-06 23:33:29
The latter cases are actually more like `$a <= $x <= $b`, and you would have to make sure that `$x` is an integer.
Brad Gilbert
2009-11-06 23:55:36
ysth
2009-11-08 06:43:15
+2
A:
In Perl6, the comparison operators are chainable.
http://perlcabal.org/syn/S03.html#Chained_comparisons:
Perl 6 supports the natural extension to the comparison operators, allowing multiple operands:
if 1 < $a < 100 { say "Good, you picked a number *between* 1 and 100." }
if 3 < $roll <= 6 { print "High roll" }
if 1 <= $roll1 == $roll2 <= 6 { print "Doubles!" }
ysth
2009-11-08 07:25:23