[英]How to find all Keys in a hash have a value in Perl
您如何确定所有哈希键是否都具有某些值?
从perldoc -f exists
:
print "Exists\n" if exists $hash{$key};
print "Defined\n" if defined $hash{$key};
print "True\n" if $hash{$key};
print "Exists\n" if exists $array[$index];
print "Defined\n" if defined $array[$index];
print "True\n" if $array[$index];
哈希或数组元素只有在已定义且已定义(如果存在)的情况下才可以为true,但相反的情况不一定成立。
my @keys_with_values = grep { defined $hash{$_} } keys %hash;
重读您的问题,似乎您正在尝试找出哈希中的任何值是否未定义,在这种情况下,您可以说
my @keys_without_values = grep { not defined $hash{$_} }, keys %hash;
if (@keys_without_values) {
print "the following keys do not have a value: ",
join(", ", @keys_without_values), "\n";
}
如果键存在,则它具有一个值(即使该值是undef
),因此:
my @keys_with_values = keys %some_hash;
您的问题不完整,因此该代码可以作为答案;-)
my %hash = (
a => 'any value',
b => 'some value',
c => 'other value',
d => 'some value'
);
my @keys_with_some_value = grep $hash{$_} eq 'some value', keys %hash;
编辑:我再次重读了问题,并决定答案可以是:
sub all (&@) {
my $pred = shift();
$pred->() or return for @_;
return 1;
}
my $all_keys_has_some_value = all {$_ eq 'some value'} values %hash;
如果您只想知道是否已定义所有值,或者任何未定义的值,则可以这样做:
sub all_defined{
my( $hash ) = @_;
for my $value ( values %$hash ){
return '' unless defined $value; # false but defined
}
return 1; #true
}
这是使用each的另一种方法。 蒂莫迪
while (my($key, $value) = each(%hash)) {
say "$key has no value!" if ( not defined $value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.