开发者

Replacing hash name with scalar in Perl

I have a hash:开发者_如何学Python

my $normal_hash = {a => '10',};
print $normal_hash;  # prints HASH(0x......)

I want to refer to this hash in the following way:

my $var = 'normal_hash';
print $$var; 

This is WRONG, but what do I need to put in there in order to get the same result?


You are trying to use symbolic references.

Don't do it.

For way more info on symbolic references, see my response to How do I use symbolic references in Perl. The original questioner asked about typeglobs, so there is some info in the post about them, as well.


Try:

my $normal_hash = {a => '10',};
print $normal_hash, "\n";
my $var = $normal_hash;
print $var, "\n";

What you were doing is called a symbolic reference, and it's not considered best practice.

To see what's in your hash, use Data::Dumper;

use Data::Dumper;
print "\$normal_hash:\n", Dumper $normal_hash;


I hope this explains the principle:

1: $hsh = { a => 1, b => 2};
2: print "Original Hash: $hsh\n";
3: my $name = 'hsh';
4: print "Hash Name: $name\n";
5: $ref = eval "\$$name";
6: print "Hash resolved from variable name: $ref\n";

Here...

Line 1 defines your hash.

Line 3 defines $name which contains the name of your hash.

Line 5 converts that name into the hash ref which you want from name of the hash variable.

Output...

Original Hash: HASH(0x8bb8880)
Hash Name: hsh
Hash resolved from variable name: HASH(0x8bb8880)

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜