How can I undefine the value for a hash key in Perl? How can my code be corrected?
#!/usr/bin/perl
use strict;
use warnings;
my %hash;
undef($hash{"a"});
undef($hash{"b"});
print scalar values %hash; # Here I need 0
print scalar keys %hash; # And 2开发者_如何转开发 here
undef($hash{"a"});
is equivalent to
$hash{"a"} = undef;
So you add key 'a' with 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 unwanted elements.
Alexandr Ciornii's point about definedness vs. existence is a very good one, but if you actually do want to know the number of defined values, you can always do:
print scalar grep { defined $_ } values %hash
Use:
undef $hash{$key};
This will undef the value for this key:
print "E" if exists $hash{$key}; # Will print E
print "D" if defined $hash{$key}; # Will not print D
精彩评论