且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Perl等同于(Python-)列表理解

更新时间: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;

我还认为输入速度太慢,因此在发布答案之前应该重新加载页面.顺便说一句,值0undef可能是处理 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.)