Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I undefine the value for a hash key in Perl?

Tags:

hash

perl

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
like image 970
Alexandr Avatar asked Dec 10 '22 18:12

Alexandr


2 Answers

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.

like image 167
Alexandr Ciornii Avatar answered Jan 09 '23 14:01

Alexandr Ciornii


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
like image 20
hobbs Avatar answered Jan 09 '23 14:01

hobbs