如何将数字与bash或Perl中的范围进行比较?

时间:2009-02-28 04:34:30

标签: perl bash range

如何编制数字与范围的比较?

  

1不在2-5

之内

  

3在2-5之内

7 个答案:

答案 0 :(得分:18)

Perl6中的情况更好。

链式比较运算符:

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

智能匹配运营商:

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

结:

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

给定/何时运营商:

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

答案 1 :(得分:12)

Perl:

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

答案 2 :(得分:11)

在bash中:

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

答案 3 :(得分:8)

smart match operator也可以在Perl 5.10中使用:

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

答案 4 :(得分:2)

在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

答案 5 :(得分:1)

自{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")

您可以测试输入是否为=~的整数:

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

答案 6 :(得分:0)

在perl

grep {/^$number$/} (1..25);
如果数字在范围内,

会给你一个真值,否则会给你一个假值。

例如:

[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:~]$ 
相关问题