How to script a comparison of a number against a range?
1 is not within 2-5
or
3 is within 2-5
How to script a comparison of a number against a range?
1 is not within 2-5
or
3 is within 2-5
Perl6
.Chained comparison operators:
if( 2 <= $x <= 5 ){
}
Smart-match operator:
if( $x ~~ 2..5 ){
}
Junctions:
if( $x ~~ any 2..5 ){
}
Given / When operators:
given( $x ){
when 2..5 {
}
when 6..10 {
}
default{
}
}
In Perl:
if( $x >= lower_limit && $x <= upper_limit ) {
# $x is in the range
}
else {
# $x is not in the range
}
In bash:
$ if [[ 1 -gt 2 && 1 -lt 5 ]]; then echo "true"; fi
$ if [[ 3 -gt 2 && 1 -lt 5 ]]; then echo "true"; fi
true
The smart match operator is available in Perl 5.10, too:
if ( $x ~~ [2..5] ) {
# do something
}
In Bash:
x=9; p="\<$x\>"; if [[ $(echo {10..20}) =~ $p ]]; then echo true; else echo false; fi
Edited to correctly handle conditions as noted in the comment below.
rangecheck () { local p="\<$1\>"; if [[ $(echo {10..20}) =~ $p ]]; then echo true; else echo false; fi; }
for x in {9..21}; do rangecheck "$x"; done
false
true
.
.
.
true
false
The [[
version of test has supported regular expressions since Bash 3.0.
[[ 3 =~ ^[2-5]$ ]]; echo $? # 0
The numeric comparison operators in test sometimes return an error if the input isn't numeric:
[[ 1a -ge 1 ]]; echo $? # value too great for base (error token is "1a")
[[ '$0' -le 24 ]] # syntax error: operand expected (error token is "$o")
You can test if the input is an integer with =~
:
x=a23; [[ "$x" =~ ^[0-9]+$ && "$x" -ge 1 && "$x" -le 24 ]]; echo $? # 1
x=-23; [[ "$x" =~ ^-?[0-9]+$ && "$x" -ge -100 && "$x" -le -20 ]]; echo $? # 0
In perl
grep {/^$number$/} (1..25);
will give you a true value if the number is in the range and a false value otherwise.
For example:
[dsm@localhost:~]$ perl -le 'print "has `$ARGV[0]`" if grep {/^$ARGV[0]$/} (1..25)' 4
has `4`
[dsm@localhost:~]$ perl -le 'print "has `$ARGV[0]`" if grep {/^$ARGV[0]$/} (1..25)' 456
[dsm@localhost:~]$