Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert hash into hash in Perl

Tags:

hash

perl

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

like image 487
Pasha Avatar asked Sep 22 '11 08:09

Pasha


People also ask

How do I append a hash in Perl?

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.

How do I undef a hash in Perl?

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.

How do I return a hash value in Perl?

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


1 Answers

%translations = (
    "phrase N" => "blah-blah",
    # ....
    "phrase M" => "something",
    %translations
    );
like image 183
Karoly Horvath Avatar answered Oct 13 '22 22:10

Karoly Horvath