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
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
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{
}
}
The smart match operator is available in Perl 5.10, too:
if ( $x ~~ [2..5] ) {
# do something
}
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:~]$
In bash:
if [[ $(echo {2..5}) =~ $x ]]; then echo true; fi