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.
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.