如何打印文字';空';对于Perl中未定义的值?

如何打印文字';空';对于Perl中未定义的值?,perl,null,undef,Perl,Null,Undef,我正在运行一个查询“descripe table”,它为“default”列返回值“null”。然而,当我试图将值从数据库打印到HTML表时,它并没有打印“null”。它总是空白的 以下是我存储数据库数据的方式: @nulls = (); while (($null) = $sth1->fetchrow_array) { push (@nulls, $null); } use strict; use warnings; my @nulls = (); whil

我正在运行一个查询“descripe table”,它为“default”列返回值“null”。然而,当我试图将值从数据库打印到HTML表时,它并没有打印“null”。它总是空白的

以下是我存储数据库数据的方式:

@nulls = ();

while (($null) = $sth1->fetchrow_array)
    {
    push (@nulls, $null);
    }
use strict;
use warnings;

my @nulls = ();
while ((my $null) = $sth1->fetchrow_array)
    {
            # before perl 5.10: use the ternary operator.
            push @nulls, defined $null ? $null : 'NULL';

            # perl 5.10 adds the defined-or operator: //
            push @nulls, $null // 'NULL';
    }

当我打印数组
@nulls
的内容时,它从不打印“null”的文本值。它总是空白的。有没有办法克服这个问题?

我不使用Perl,但在我使用的其他每种语言中,都必须测试null值。如果为空,则打印字符串文字“null”。

从,它将返回空值作为“undef”。

正如Chris J所说,空值作为未定义的值返回

如果启用了警告,则在打印值时会收到“打印中未定义值”警告。使用
strict
warnings
pragmata可以节省大量调试时间。
diagnostics
pragma在标准警告和致命错误中添加了额外的解释文本

捕获和替换来自数据库的空值非常容易:

@nulls = ();

while (($null) = $sth1->fetchrow_array)
    {
    push (@nulls, $null);
    }
use strict;
use warnings;

my @nulls = ();
while ((my $null) = $sth1->fetchrow_array)
    {
            # before perl 5.10: use the ternary operator.
            push @nulls, defined $null ? $null : 'NULL';

            # perl 5.10 adds the defined-or operator: //
            push @nulls, $null // 'NULL';
    }
或者,您可以按照上面显示的方式构建
@nulls
数组,然后在显示时更改nulls

my @pre_5_10  = map { defined $_ ? $_ : 'NULL' } @nulls;
my @perl_5_10 = map { $_ // 'NULL' } @nulls;

您不会说您正在使用哪个数据库,但如果您不介意使用不可移植的解决方案,您可以在SQL级别执行,例如在Oracle中:

select NVL(some_column, 'NULL')
from some_table

也不是Perl的家伙,但在我使用的语言中,数据库中的“null”与语言中的“null”不同。因此,应该注意测试数据库的“null”值,而不是语言的“null”值。DBI在数据库null值和Perl的undef值之间始终映射。