更新时间:2023-02-12 21:47:06
#!/usr/bin/env perl
use strict;
use warnings;
my %data = ( A => undef, B => 'yes', C => undef );
my @keys = grep { defined $data{$_} } keys %data;
print "Key: $_\n" for @keys;
我还认为输入速度太慢,因此在发布答案之前应该重新加载页面.顺便说一句,值0
或undef
可能是处理 null 值的好方法,但请确保您记住正在使用的值.错误值和未定义值在Perl中不是同一回事.需要说明的是:undef
在布尔测试中返回false,但0
也是.如果0
是有效值,那么您要显式测试定义性,而不仅仅是真实性. (我之所以这样提,是因为James参加了0
,而我却选择了另一种方式,所以您可能不知道这是否重要.)
I also think that I type too slowly, and that I should reload the page before posting answers. By the way, either a value of 0
or undef
can be a good way to handle null values, but make sure you remember which you're using. A false value and and undefined value aren't the same thing in Perl. To clarify: undef
returns false in a boolean test, but so does 0
. If 0
is a valid value, then you want to explicitly test for definedness, not simply truth. (I mention it because James went for 0
and I went the other way, and you may or may not know if it matters.)