此代码无法识别它似乎识别的任何键:
if( $key =~ /upsf|free|ground|sla|pickup|usps/ )
所以我将其更改为:
if( $key eq 'upsf' || $key eq 'free'
|| $key eq 'ground' || $key eq 'sla'
|| $key eq 'pickup' || $key eq 'usps' )
在我看来它们在功能上是等效的,所以我试图找出第一个失败的原因。它是 Windows 7 上 XAMPP 下的 Perl,也是 Linux 上 Apache2 下的 Perl。
这会在 Windows 和 Linux 上打印“shelf it”。
$key = 'upsf';
if( $key =~ /^(upsf|free|ground|sla|pickup|usps)$/ ) {
print 'ship it';
} else {
print 'shelf it';
}
最佳答案
它们并不相等,因为第一个中的比较运算符是“=~”(“包含”), 其中第二个是“eq”(“显式匹配,等于”)。
第一个到底是怎么失败的?您对 $key 的测试值是多少?
$key = 'xxx';
if( $key =~ /upsf|free|ground|sla|pickup|usps/ ) {
print 'ship it';
} else {
print 'shelf it';
}
将打印“搁置它”。 例如, $key='xusps' 会打印 'ship it',通过 '=~' 运算符匹配(“包含”),这可能不是您的目标。
关于regex - Perl 匹配正则表达式的哪些细微差别会引起头痛?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11674936/