Reputation: 35107
How do you determine if all hash keys have some value ?
Upvotes: 2
Views: 3071
Reputation: 4872
Here's one more way, using each. TIMTOWDI
while (my($key, $value) = each(%hash)) {
say "$key has no value!" if ( not defined $value);
}
Upvotes: 0
Reputation: 34130
If all you want is to know if all values are defined, or any undefined this will do that:
sub all_defined{
my( $hash ) = @_;
for my $value ( values %$hash ){
return '' unless defined $value; # false but defined
}
return 1; #true
}
Upvotes: 0
Reputation: 26141
Your question is incomplete thus this code can be answer ;-)
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;
EDIT: I had reread question again and decided that answer can be:
sub all (&@) {
my $pred = shift();
$pred->() or return for @_;
return 1;
}
my $all_keys_has_some_value = all {$_ eq 'some value'} values %hash;
Upvotes: 1
Reputation: 64939
Feed the result of keys into grep with defined
my @keys_with_values = grep { defined $hash{$_} } keys %hash;
Rereading your question, it seems like you are trying to find out if any of the values in your hash are undefined, in which case you could say something like
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";
}
Upvotes: 7
Reputation: 944443
If the key exists, it has a value (even if that value is undef
) so:
my @keys_with_values = keys %some_hash;
Upvotes: 3
Reputation: 74272
From 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];
A hash or array element can be true only if it's defined, and defined if it exists, but the reverse doesn't necessarily hold true.
Upvotes: 10