Perl获取作为定义值的散列中的所有键

时间:2015-02-13 02:03:51

标签: perl

if ($type eq 'running') {
    @keys = sort {${$jobs{$type}}{$a}{stime} cmp ${$jobs{$type}}{$b}{stime}} keys % {$jobs{$type}};
} elsif ($type eq 'failed' or $type eq 'interrupted') {
    @keys = sort {${$jobs{$type}}{$a}{etime} cmp ${$jobs{$type}}{$b}{etime}} keys % {$jobs{$type}};
}

 Use of uninitialized value in string comparison (cmp) at /u/eugenep/bedrock/source/br-brock/bin/../bin/brock line 585, <$BR> line 81.

我收到了上述错误。 如何以有效的方式过滤掉已定义值的键?

我不想做类似的事情:

@k_w_values = ();
foreach $k ($jobs{$type}) {
    if (defined $jobs{$type}{$k}{stime}) {
       append $k to @k_w_values
    }
}       

有没有像单行程?

1 个答案:

答案 0 :(得分:2)

使用grep (perlfunc)过滤您的密钥:

@keys = sort {${$jobs{$type}}{$a}{stime} cmp ${$jobs{$type}}{$b}{stime}}
            grep (defined($jobs{$type}->{$_}{stime}), keys % {$jobs{$type}});

@keys = sort {${$jobs{$type}}{$a}{etime} cmp ${$jobs{$type}}{$b}{etime}} 
            grep (defined($jobs{$type}->{$_}{etime}), keys % {$jobs{$type}});