2014-03-12 113 views
0
my $line = "hello"; 
print ($line == undef); 

該檢查應該是假的,因爲$行不是未定義的(我在第一行中定義了它)。爲什麼這段代碼片段打印出'1'?爲什麼這個字符串undef check返回true?

+0

可能重複的[==之間的差異,和= EQ](http://stackoverflow.com/questions/18396049/difference -between-and-eq) – mob

回答

4

它在做什麼,你說什麼。

print ($line == undef); 

你打印出一個布爾值,因爲($line == undef)是布爾語句。

==數字等於。由於$line是文本,因此它的值爲0。數字上也是undef。因此($line == undef)是正確的。

你應該總是把你的程序的頂部以下內容:

use strict; 
use warnings; 

還有其他一些雜注人說,但這些是兩個最重要的。他們會發現90%的錯誤。試試這個程序:

use strict; 
use warnings; 
my $line = "hello"; 
print ($line == undef) 

您將獲得:

Use of uninitialized value in numeric eq (==) at ./test.pl line 6. 
Argument "hello" isn't numeric in numeric eq (==) at ./test.pl line 6. 

當然,我有一個未初始化的價值!我正在使用undef。而且,當然hello不是數字值。

我不完全確定你想要什麼。如果未定義,是否要打印hello?你想看看布爾語句的值嗎?

那麼\nprint不會放在行尾?你想要那個嗎?因爲print可以容易遺忘\n錯誤,我更喜歡使用say

use strict; 
use warnings; 
use feature qw(say); # Say is like print but includes the ending `\n` 

my $line = "hello"; 
say (not defined $line); # Will print null (false) because the line is defined 
say (defined $line);  # Will print "1" (true). 
say ($line ne undef);  # Will print '1' (true), but will give you a warning. 
say $line if defined line; # Will print out $line if $line is defined 
+0

哇,這很詳細。非常感謝。 – santi

4

始終把

use strict; use warnings; 

use Modern::Perl; 

你會看到一些錯誤:

Use of uninitialized value in numeric eq (==) at /tmp/sssl.pl line 3. 
Argument "hello" isn't numeric in numeric eq (==) at /tmp/sssl.pl line 3. 

要測試一個變量的定義,使用方法:

print "variable defined" if defined $variable; 

爲了測試對另一個字符串的字符串,使用方法:

if ($string eq $another_string) { ... } 
+0

啊!謝謝,我以爲可以使用undef,因爲我們在java中使用null – santi

相關問題