简体   繁体   中英

Perl get all keys in a hash that as defined values

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.

I am getting the above error. How can I filter out keys that has defined values in efficient way?

i dont want to do something like:

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

Is there like one-liner?

Filter your keys with grep (perlfunc) :

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

and

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM