Search code examples
perlhashhashref

How can I reference a hash using a variable name?


I have a set of pre-defined hash tables and I want to reference one of those hashes using a variable name and access a key value. The following code just returns null even though the hash is populated. What am I doing wrong here, or is there a better way to achieve this?

my %TEXT1 = (1 => 'Hello World',);
my %TEXT2 = (1 => 'Hello Mars',);
my %TEXT3 = (1 => 'Hello Venus',);

my $hash_name = 'TEXT1';

my $hash_ref = \%$hash_name;
print ${$hash_ref}{1};  #prints nothing

Solution

  • Use a hash to contain your hashes.

    my %texts = (
        TEXT1 => { 1 => 'Hello world', },
        TEXT2 => { 1 => 'Hello Mars', },
        TEXT3 => { 1 => 'Hello Venus', },
    )
    
    my $hash_name = 'TEXT1';
    
    print $texts{$hash_name}{1}, "\n";