How can I reference a hash with a variable name?

I have three hash with the name %hash1, %hash2, %hash3. I need to reference each hash by a variable and don't know 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 simple, relatively empty question, so I apologize for that.

+3
source share
2 answers

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 links instead of using symbolic links. It is very easy to get symbolic links incorrectly and can be difficult to debug.

Here is how you could use symbolic links, but I would advise you to do so.

#!/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';

  # ...

}
+17
source

To link to a hash by reference, you can do this in one of two ways.

my $ref_hash = \%hash;

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

, , .

1 ( )

print $ref_hash->{key};

2

print ${$ref_hash}{key};

, .

+1

Source: https://habr.com/ru/post/1714548/


All Articles