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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With