Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default for undefined hash values

Tags:

hash

perl

I have a hash whose values are mostly integers, but some are undefined. I would like to set all of these undefined values to zero, either with a for loop or, preferably, with a more elegant method. Can someone suggest a solution?

like image 244
Wes Field Avatar asked Jul 04 '13 19:07

Wes Field


1 Answers

Both methods are using foreach,

for my $key (keys %hash) {
  $hash{$key} //= 0;

}

$_ //= 0 for values %hash;

//= operator test if variable is undefined and assign new value when it is.

like image 97
mpapec Avatar answered Sep 22 '22 12:09

mpapec