user1712832
user1712832

Reputation: 29

Copy a hash out of a hash reference

I have a hash reference to a hash of hashes.

ref -> hash1
hash2
etc...

I am trying to copy 2 hashes to use to compare against each other.

   my %hash1 = %$ref->{ $name1}; // but I can't get it to work.  
   my %hash2 = %$ref->{ $name2};

I get: Reference found where even-sized list expected at.

I know I am not declaring this right, so any help would be appreciated.

Upvotes: 2

Views: 199

Answers (2)

Pavel Vlasov
Pavel Vlasov

Reputation: 3465

You have error here: %$ref->{ $name1};, it's incorrect deference here. Please check my example below.

#!/usr/bin/perl

use strict;
use Data::Dumper;

my $ref = {
    hash1 => { a => 1, b => 2 },
    hash2 => { c => 3, d => 3 },
};

my $name = 'hash1';
my %hash = %{ $ref->{$name} }; # right dereference
print Dumper(\%hash);

Upvotes: 4

snoofkin
snoofkin

Reputation: 8895

due to operator precedence you will need to do it this way:

my %hash1 = %{ $ref->{$name} };

Upvotes: 3

Related Questions