How do you determine if all hash keys have some value ?
+7
A:
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.
Alan Haggai Alavi
2009-07-03 09:35:50
exists and delete on array elements have interesting and not always useful properties. If you really need those, you're best off using a hash.
ysth
2009-07-03 16:29:11
+4
A:
If the key exists, it has a value (even if that value is undef
) so:
my @keys_with_values = keys %some_hash;
David Dorward
2009-07-03 09:37:45
+7
A:
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";
}
Chas. Owens
2009-07-03 09:38:42
+1
A:
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;
Hynek -Pichi- Vychodil
2009-07-03 15:32:29
A:
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
}
Brad Gilbert
2009-07-04 13:59:57