如何在 bash 或 Perl 中将数字与范围进行比较?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/597497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I compare a number against a range in bash or Perl?
提问by hillu
How to script a comparison of a number against a range?
如何编写数字与范围的比较脚本?
1 is not within 2-5
1 不在 2-5 之内
or
或者
3 is within 2-5
3 在 2-5 以内
回答by Brad Gilbert
It's even better in Perl6
.
在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{
}
}
回答by Adnan
In Perl:
在 Perl 中:
if( $x >= lower_limit && $x <= upper_limit ) {
# $x is in the range
}
else {
# $x is not in the range
}
回答by jcrossley3
In bash:
在 bash 中:
$ if [[ 1 -gt 2 && 1 -lt 5 ]]; then echo "true"; fi
$ if [[ 3 -gt 2 && 1 -lt 5 ]]; then echo "true"; fi
true
回答by hillu
The smart match operatoris available in Perl 5.10, too:
该智能匹配运营商可以在Perl 5.10,太:
if ( $x ~~ [2..5] ) {
# do something
}
回答by Paused until further notice.
In Bash:
在 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="\<\>"; 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
回答by Lri
The [[
version of test has supported regular expressions since Bash 3.0.
该[[
测试版本以来的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")
[[ '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
' -le 24 ]] # syntax error: operand expected (error token is "$o")
You can test if the input is an integer with =~
:
您可以测试输入是否为整数=~
:
grep {/^$number$/} (1..25);
回答by dsm
In perl
在 perl 中
[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:~]$
will give you a true value if the number is in the range and a false value otherwise.
如果数字在范围内,将为您提供真值,否则为假值。
For example:
例如:
##代码##