I created a hash in Perl my %hash = (2 => 'dog', 1 => 'cat');
When I print $hash{3}
it errors (use of uninitialzed value in print
) which is expected. But is there a way to default a value if not in hash?
my $value = exists($hash{$k}) ? $hash{$k} : 'default';
To actually change the hash, use
$hash{$k} = 'default' if !exists($hash{k});
If $hash{$k}
is always defined if it exists, you could also use
my $value = defined($hash{$k}) ? $hash{$k} : 'default';
which can be reduced to
my $value = $hash{$k} // 'default'; # 5.10+
To actually change the hash, use
$hash{$k} = 'default' if !defined($hash{k});
or
$hash{$k} //= 'default'; # 5.10+
If $hash{$k}
is always true if it exists, you could also use
my $value = $hash{$k} ? $hash{$k} : 'default';
which can be reduced to
my $value = $hash{$k} || 'default';
To actually change the hash, use
$hash{$k} = 'default' if !$hash{k};
or
$hash{$k} ||= 'default';
I suggest you take a look at the
Hash::DefaultValue
module which allows you to specify a value for a hash that will be returned instead of undef
if an element doesn't exist
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