tags:

views:

333

answers:

2

I have three hashes named %hash1, %hash2, %hash3. I need to reference each hash by variable and am not sure how to do it.

#!/usr/bin/perl

# Hashes %hash1, %hash2, %hash3 are populated with data.

@hashes = qw(hash1 hash2 hash3);
foreach $hash(@hashes){
    foreach $key(keys $$hash){
          .. Do something with the hash key and value
    }
}

I know this is a fairly simplistic, comparatively noob question so my apologies for that.

+15  A: 

This should work for you.

#!/usr/bin/perl
use strict;
use warnings;

my( %hash1, %hash2, %hash3 );

# ...

# load up %hash1 %hash2 and %hash3

# ...

my @hash_refs = ( \%hash1, \%hash2, \%hash3 );

for my $hash_ref ( @hash_refs ){
  for my $key ( keys %$hash_ref ){
    my $value = $hash_ref->{$key};

    # ...

  }
}

It uses hash references, instead of using symbolic references. It is very easy to get symbolic references wrong, and can be difficult to debug.

This is how you could have used symbolic references, but I would advise against it.

#!/usr/bin/perl
use strict;
use warnings;

# can't use 'my'
our( %hash1, %hash2, %hash3 );

# load up the hashes here

my @hash_names = qw' hash1 hash2 hash3 ';
for my $hash_name ( @hash_names ){
  print STDERR "WARNING: using symbolic references\n";

  # uh oh, we have to turn off the safety net
  no strict 'refs';

  for my $key ( keys %$hash_name ){
    my $value = $hash_name->{$key};

    # that was scary, better turn the safety net back on
    use strict 'refs';

    # ...

  }

  # we also have to turn on the safety net here
  use strict 'refs';

  # ...

}
Brad Gilbert
+1 For typing faster than me :)
Swish
Many many +1's for not showing the OP how to use symbolic references ;-) http://perldoc.perl.org/perlfaq7.html#How-can-I-use-a-variable-as-a-variable-name%3F ... *Beginners often think they want to have a variable contain the name of a variable.*
Sinan Ünür
Sorry for adding the scary symbolic references version :-(
Brad Gilbert
Although, hopefully, I have shown the trouble with doing that.
Brad Gilbert
why is this such a common question? Where is this used|thought to be a good idea?
MkV
+1  A: 

To reference a hash by a reference you can do it one of two ways.

my $ref_hash = \%hash;

or create an anonymous referenced hash

my $ref_hash = { 
    key => value, 
    key => value
}

Now in order to access this hash you'll need to de-reference the variable or use the arrow syntax.

Example 1 (Arrow syntax)

print $ref_hash->{key};

Example 2

print ${$ref_hash}{key};

I hope that helps.

Logan
The question was about using symbolic references.
Brad Gilbert
@Brad: the question is about getting the job done. I'm sure he'd be happy to use whatever works. :)
brian d foy