I have a simple hash defined somewhere in the main file
our %translations = (
"phrase 1" => "translation 1",
# ... and so on
);
In another file I want to add some more translations. That is, I want to do something like this:
push our %translations, (
"phrase N" => "blah-blah",
# ....
"phrase M" => "something",
);
Of course this code wouldn't work: push
doesn't work with hashes. So my question is: what is a simple and elegant way to insert a hash of values into an existing hash?
I wouldn't want to resort to
$translations{"phrase N"} = "blah-blah";
# ....
$translations{"phrase M"} = "something";
since in Perl you're supposed to be able to do things without too much repetition in your code...
To append a new value to the array of values associated with a particular key, use push : push @{ $hash{"a key"} }, $value; The classic application of these data structures is inverting a hash that has many keys with the same associated value. When inverted, you end up with a hash that has many values for the same key.
undef $hash{$key} and $hash{$key} = undef both make %hash have an entry with key $key and value undef . The delete function is the only way to remove a specific entry from a hash. Once you've deleted a key, it no longer shows up in a keys list or an each iteration, and exists will return false for that key.
$hash{key} is a single element within the hash. Therefore, \%hash is a reference to %hash , i.e., the whole hash, which appears to be what you intend to return in this case. \$hash{key} is a reference to a single element.
%translations = (
"phrase N" => "blah-blah",
# ....
"phrase M" => "something",
%translations
);
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