Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default a value for missing hash

Tags:

perl

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?

like image 820
user3525290 Avatar asked May 09 '18 20:05

user3525290


2 Answers

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';
like image 68
ikegami Avatar answered Nov 03 '22 00:11

ikegami


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

like image 24
Borodin Avatar answered Nov 02 '22 22:11

Borodin