2012-02-13 80 views
3

我只是想檢查一個字符串是否等於「%2B」,如果是這樣,我將其更改爲「+」。 問題在於比較。perl中%2B的比較

if ($lastItem == "%2B"){ 
    $lastItem = "+"; 
} 

當$ lastItem是完全不同的東西(如「hello」)時,它仍然會進入語句。我一直在困擾着我的大腦,我無法分辨出錯的地方。 %2B有特殊含義嗎?我對perl很陌生。

感謝

回答

8

您需要使用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 
+0

哦,哈哈我覺得自己像一個白癡。謝謝 – user1126345 2012-02-13 05:27:38

+1

@ user1126345這是一個常見的錯誤。別客氣。 – TLP 2012-02-13 05:33:11

+0

@ user1126345如果您覺得這回答了您的問題,您可以點擊左邊的複選標記以「接受」它。 – TLP 2012-02-13 05:37:33

3

我覺得你真的想以下幾點:

if ($lastItem eq "%2B") { 

要注意,如果您使用了use warnings,這個問題本來就容易被發現,因爲這一個班輪將證明這一點很重要:

use URI::Escape qw(uri_unescape); 

my $unescaped_last_item = uri_unescape($escaped_last_item); 

URI::Escape

請使用use strict; use warnings;

2

另一個例子是,打開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