0

I have a hash:

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?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
Uni
  • 3
  • 2

3 Answers3

3

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.

Community
  • 1
  • 1
daotoad
  • 26,689
  • 7
  • 59
  • 100
1

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

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.

chkdsk
  • 1,187
  • 6
  • 20
  • 4
    string eval is almost never what you are looking for. it is needed in this example because you are trying to perform a symbolic dereference on a lexical variable which is not possible. the string eval provides a way around this, but speaks to a much larger problem with the design of your program. – Eric Strom Mar 11 '11 at 02:11
  • 1
    Of course this is a really bad idea. But if that is what @Uni wanted to do this solution provides what he wants to do!!! I don't think my solution deserves the -1 it has as there is nothing wrong with the solution. – chkdsk Mar 11 '11 at 20:03
  • => I did not down vote you, but my guess as to why is that you are recommending string `eval` to a novice without explaining that just because you can, you shouldn't. Basically, any time where you have the above situation, the problem is better solved by placing the variables you want to reference by string name into a hash, and then referencing them by key. Not only is it faster, but it is much safer. – Eric Strom Mar 11 '11 at 22:07