質問

Is it possible to merge two hashes like so:

%one = {
    name    => 'a',
    address => 'b'
};

%two = {
    testval => 'hello',
    newval  => 'bye'        
};

$one{location} = %two;

so the end hash looks like this:

%one = {
    name    => 'a',
    address => 'b',
    location => {
        testval => 'hello',
        newval  => 'bye'
    }
}

I've had a look but unsure if this can be done without a for loop. Thanks :)

役に立ちましたか?

解決

One can't store a hash in a hash since the values of hash elements are scalars, but one can store a reference to a hash. (Same goes for storing arrays and storing into arrays.)

my %one = (
   name    => 'a',
   address => 'b',
);

my %two = (
   testval => 'hello',
   newval  => 'bye',     
);

$one{location} = \%two;

is the same as

my %one = (
   name    => 'a',
   address => 'b',
   location => {
      testval => 'hello',
      newval  => 'bye',
   },
);

他のヒント

If you use

$one{location} = \%two

then your hash will contain a reference to hash %two, so that if you modify it with something like $one{location}{newval} = 'goodbye' then %two will also be changed.

If you want a separate copy of the data in %two then you need to write

$one{location} = { %two }

after which the contents of %one are independent of %two and can be modified separately.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top