I would like to know how to determine the value for a hash key in Perl. Can someone fix my code?
#!/usr/bin/perl use strict; use warnings; my %hash; undef($hash{"a"}); undef($hash{"b"}); print scalar values %hash; # i need here 0 print scalar keys %hash; # and here 2
The other answer point about certainty and existence is very good, but if you really want to know the number of certain values, you can always do
print scalar grep { defined $_ } values %hash
undef($hash{"a"});
equivalently
$hash{"a"}=undef;
So you add the key 'a' with the value undef. To delete a value from a hash, use "delete".
delete $hash{"a"};
It is not possible to have different sizes of "keys" and "values" for the same hash. You can use grep to filter out unwanted elements.
undef $hash{$key};
this will override the value for this key:
print "E" if exists $hash{$key}; # will print E print "D" if defined $hash{$key}; # will not print D