Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand for adding new values to a hash of arrays

Tags:

perl

Below is a generalization of a block of code that I keep having to write when i want to build up a hash of arrays inside some sort of loop.

#get value and key that I want to use
my $value = getvalue();
my $key = getKey();

#add value to hash using key
if($hash_of_arrays{$key}){
    push(@{$hash_of_arrays{$key}}, $value);
}
else{
    $hash_of_arrays{$key} = [$value];
}

The if statement is very tedious to write for such a simple task but it needs to be done because pushing a value when its key is undefined in the hash causes problems. I'm just wondering if there is any shorthand to writing this - one where I dont have to write out $hash_of_arrays{$key} three times.

like image 636
MattLBeck Avatar asked Aug 07 '11 15:08

MattLBeck


1 Answers

push @{ $HoA{$key} }, $value; works perfectly well and is the recommended thing to do. If your code that uses it has "problems", then ask about those problems instead.

like image 88
hobbs Avatar answered Nov 25 '22 07:11

hobbs