How to compare a number with a range in bash or Perl?

How does a script compare numbers with a range?

1 is not within 2-5

or

3 is in the range 2-5

+3
source share
7 answers

This is even better at Perl6.

Comparison Chains:

if( 2 <= $x <= 5 ){
}

Smart-match statement:

if( $x ~~ 2..5 ){
}

joints:

if( $x ~~ any 2..5 ){
}

Given / When Operators:

given( $x ){
  when 2..5 {
  }
  when 6..10 {
  }
  default{
  }
}
+18
source

In Perl:

if( $x >= lower_limit && $x <= upper_limit ) {
   # $x is in the range
}
else {
   # $x is not in the range
}
+12
source

bash:

$ if [[ 1 -gt 2 && 1 -lt 5 ]]; then echo "true"; fi
$ if [[ 3 -gt 2 && 1 -lt 5 ]]; then echo "true"; fi
true
+11

smart match Perl 5.10:

if ( $x ~~ [2..5] ) {
    # do something
}
+8

Bash:

x=9; p="\<$x\>"; if [[ $(echo {10..20}) =~ $p ]]; then echo true; else echo false; fi

, .

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
+2

[[ Bash 3.0.

[[ 3 =~ ^[2-5]$ ]]; echo $? # 0

, :

[[ 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 check 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
+1
source

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:~]$ 
0
source

Source: https://habr.com/ru/post/1703991/


All Articles