Reputation: 101
I declare a hash in Perl by doing this:
my %hash = ();
I go on adding elements to the hashes. Sometimes, $hash{$x}
is not defined, meaning it probably is null
. So when I try to print it, I do not get anything. I expect to see a 0
in case that entry $x
is not defined. Can someone tell me how do I do this? How do I initialize hash elements to 0
initially?
Upvotes: 2
Views: 1872
Reputation: 1
It is possible to initialise the hash.
my %hash = ();
@hash{@keys} = (0) x @keys;
This will create a hash, give it an element for each key and then set the values to an array of 0's as long as the key array.
Upvotes: 0
Reputation: 1
Note that one doesn't test if a key is defined, but if a key exists using the exists key word. One tests to see if the value is defined with the defined keyword.
print "Exists\n" if exists $hash{$key};
print "Defined\n" if defined $hash{$key};
print "True\n" if $hash{$key};
The first tests if the key exists, the 2nd if the value is defined and the 3rd if the value returns a true value.
Upvotes: 0
Reputation: 222
There is no such of thing as default value for non defined hash key
the correct way to manipulate hash is to test if your key is defined, with 'defined' function (see perl defined)
[~]=> perl -e '%x = (a=>1, c=>5); for (a..d) { print "$_ => " . (defined $x{$_} ? $x{$_} :0) . "\n" }'
a => 1
b => 0
c => 5
d => 0
Upvotes: 0
Reputation: 52506
Instead of trying to set a default value, you can print a default value when you encounter an undefined value by using the defined-or operator, //
(works for Perl 5.10 and higher).
In this example, when you print your hash elements, you either print the element, or if it is not defined, 0
:
use 5.010;
say $hash{$x} // 0;
Upvotes: 6