2

是否可以像这样合并两个哈希:

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

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

$one{location} = %two;

所以结束哈希看起来像这样:

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

我看过但不确定这是否可以在没有 for 循环的情况下完成。谢谢 :)

4

2 回答 2

6

由于散列元素的值是标量,因此无法将散列存储在散列中,但可以存储对散列的引用。(存储数组和存储到数组中也是如此。)

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

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

$one{location} = \%two;

是相同的

my %one = (
   name    => 'a',
   address => 'b',
   location => {
      testval => 'hello',
      newval  => 'bye',
   },
);
于 2014-03-12T16:24:36.883 回答
3

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.

于 2014-03-12T17:01:29.217 回答