2014-03-12 151 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

相关问题