user3878370
user3878370

Reputation: 31

Can I access a Perl hash using a scalar variable for its name?

I'm wondering if I can use a variable to access a hash.

For instance:

my $var = "nameOfHash";
my $nameOfHash{'foo'} = "bar";

print $var{'foo'};

In the above sample, the behavior I desire is for it to return the string "bar," but clearly my code isn't quite correct.

Upvotes: 1

Views: 152

Answers (1)

choroba
choroba

Reputation: 242208

Why do you need it? You can use a hash of hashes (HoH) instead:

my %hoh;
$hoh{nameOfHash}{foo} = 'bar';
print $hoh{nameOfHash}{foo};

See Why it's stupid to `use a variable as a variable name' for an explanation of what's wrong with the original idea.

Upvotes: 5

Related Questions