我只是想检查一个字符串是否等于“%2B”,如果是这样,我将其更改为“+”。 问题在于比较。perl中%2B的比较
if ($lastItem == "%2B"){
$lastItem = "+";
}
当$ lastItem是完全不同的东西(如“hello”)时,它仍然会进入语句。我一直在困扰着我的大脑,我无法分辨出错的地方。 %2B有特殊含义吗?我对perl很陌生。
感谢
我只是想检查一个字符串是否等于“%2B”,如果是这样,我将其更改为“+”。 问题在于比较。perl中%2B的比较
if ($lastItem == "%2B"){
$lastItem = "+";
}
当$ lastItem是完全不同的东西(如“hello”)时,它仍然会进入语句。我一直在困扰着我的大脑,我无法分辨出错的地方。 %2B有特殊含义吗?我对perl很陌生。
感谢
您需要使用eq
比较字符串时,或Perl会尝试将字符串转换为数字(这将是0
),你会发现这样古怪的"a" == 0
评价如此。当比较两个字符串时,您当然会得到if (0 == 0)
,这是您所描述的问题。
$ perl -wE 'say "yes" if ("foo" == "bar")'
Argument "bar" isn't numeric in numeric eq (==) at -e line 1.
Argument "foo" isn't numeric in numeric eq (==) at -e line 1.
yes
我觉得你真的想以下几点:
if ($lastItem eq "%2B") {
要注意,如果您使用了use warnings
,这个问题本来就容易被发现,因为这一个班轮将证明这一点很重要:
use URI::Escape qw(uri_unescape);
my $unescaped_last_item = uri_unescape($escaped_last_item);
请使用use strict; use warnings;
!
另一个例子是,打开use warnings
可以更简单地找出错误。
$ perl -Mwarnings -e'$l = "x"; if ($l == "%2B") { print "match\n" }'
Argument "%2B" isn't numeric in numeric eq (==) at -e line 1.
Argument "x" isn't numeric in numeric eq (==) at -e line 1.
match
哦,哈哈我觉得自己像一个白痴。谢谢 – user1126345 2012-02-13 05:27:38
@ user1126345这是一个常见的错误。别客气。 – TLP 2012-02-13 05:33:11
@ user1126345如果您觉得这回答了您的问题,您可以点击左边的复选标记以“接受”它。 – TLP 2012-02-13 05:37:33