0

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
Colin R. Turner
  • 1,323
  • 15
  • 24
  • It would help a lot if you explained what you expected `my $hash_ref = \%$hash_name` to do. – Borodin Oct 21 '17 at 23:44
  • I want hash_ref to refer to a hash defined by the variable name. Edited question to clarify. – Colin R. Turner Oct 22 '17 at 09:17
  • See also [Whenever you find yourself postfixing variable names with an integer index, realize that you should have used an array instead](https://stackoverflow.com/questions/1549685/how-can-i-use-a-variable-as-a-variable-name-in-perl). – Sinan Ünür Oct 23 '17 at 14:47

3 Answers3

5

The code you have works just fine*

%TEXT = (1 => abc, 42 => def);
$name = 'TEXT';
print ref($name);         #  ""
no strict 'refs';
print ${$name}{1};        #  "abc"
print $name->{42}         #  "def"
$ref = \%$name;
print ref($ref);          #  "HASH"
print $ref->{1};          #  "abc"
print ${$ref}{42};        #  "def"

The main thing that you are doing wrong is making your code an unmaintainable mess, and that is why this sort of thing is not allowed under use strict 'refs'.

* - unless you are running under use strict 'refs', which you should be

mob
  • 117,087
  • 18
  • 149
  • 283
3

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";
shawnhcorey
  • 3,545
  • 1
  • 15
  • 17
0

The following code is assignment to a scalar, not to a hash:

my $hash_name = 'TEXT';

The following code is assignment to a hash:

my %hash = ( alpha => 'beta', gamma => 'delta' );

To print the value of a single element from the hash, you say:

print $hash{alpha}, "\n";

You can take a reference to that hash and assign that to a variable:

my $hashref = \%hash;

And from that you can print a single element from that hashref:

print $hashref->{alpha}, "\n";
James E Keenan
  • 281
  • 2
  • 10
  • 1
    This doesn't answer my question. I want to reference the hash with the name taken from a scalar variable. In other words, I have a set of hash tables already defined and I need to access values from any one of those tables depending on user input. So the scalar will define the name of the hash, then I want to define the hash_ref using that name. Sorry if this wasn't clear. – Colin R. Turner Oct 22 '17 at 09:33