Saket
Saket

Reputation: 46137

assign a hash into a hash

I wish to assign a hash (returned by a method) into another hash, for a given key.

For e.g., a method returns a hash of this form:

hash1->{'a'} = 'a1';
hash1->{'b'} = 'b1';

Now, I wish to assign these hash values into another hash inside the calling method, to get something like:

hash2->{'1'}->{'a'} = 'a1';
hash2->{'1'}->{'b'} = 'b1';

Being new to perl, I'm not sure the best way to do this. But sounds trivial...

Upvotes: 0

Views: 157

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753695

Your sub might be:

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

sub mystery
{
    my($hashref) = { a => 'a1', b => 'b1' };
    return $hashref;
}

my $hashref1 = mystery;
print "$hashref1->{a} and $hashref1->{b}\n";
my $hashref2 = { 1 => $hashref1 };
print "$hashref2->{1}->{a} and $hashref2->{1}->{b}\n";

One key point is that your notation for accessing the variables with the -> arrow operator is dealing with hash refs, not with plain hashes.

Upvotes: 3

amon
amon

Reputation: 57600

We have a 1st and a 2nd hash:

my %hash1 = (
  a => 'a1',
  b => 'b1');
my %hash2 = (1 => undef);

We can only assign scalar values to hashes, but this includes references. To take a reference, use the backslash operator:

$hash2{1} = \%hash1;

We can now dereference the values almost as in your example:

print $hash2{1}->{a}; # prints "a1"

Be carefull to use the correct sigil ($@%) as appropriate. Use the sigil of the data type you expect, wich is not neccessarily the type you declared.

"perldoc perlreftut" might be interesting.

Upvotes: 1

Related Questions