绑定两个Perl哈希值(不是两个匿名哈希值)

TVN*_*ack 1 perl hash

为了重用一些已编写的代码库,我需要将hash(%bar)伪装成另一个hash(%foo),以便在绑定%bar可以看到所做的每个更改.%foo

使用匿名哈希构造,很容易:只需将ref复制barfoo ($foo = $bar;)的ref中.

如何"不使用"匿名哈希(因为我必须重用的代码不使用匿名哈希构造)?这是唯一可能的吗?

谢谢.

use strict;
use Data::Dumper;

my  %foo = ();
my  %bar = ();

%foo = %bar;    # This won't work as it copies %bar into %foo as at the current time.

$bar{A}->{st} = 'a';
$bar{A}->{qt} = 'a';
$bar{B}->{st} = 'b';
$bar{B}->{qt} = 'b';

# $foo{A}->{st}  doesn't exist
Run Code Online (Sandbox Code Playgroud)

当然,匿名哈希构造本来就是一种祝福.

use strict;
use Data::Dumper;

my  $foo = {};
my  $bar = {};

$foo = $bar;   # This works fine.

$bar->{A}->{st} = 'a';
$bar->{A}->{qt} = 'a';
$bar->{B}->{st} = 'b';
$bar->{B}->{qt} = 'b';

print STDOUT "foo\n---\n";
print Dumper($foo) . "\n\n";

print STDOUT "bar\n---\n";
print Dumper($bar) . "\n\n";
Run Code Online (Sandbox Code Playgroud)

产生预期结果:

foo
---
$VAR1 = {
          'B' => {
                   'st' => 'b',
                   'qt' => 'b'
                 },
          'A' => {
                   'qt' => 'a',
                   'st' => 'a'
                 }
        };


bar
---
$VAR1 = {
          'B' => {
                   'st' => 'b',
                   'qt' => 'b'
                 },
          'A' => {
                   'qt' => 'a',
                   'st' => 'a'
                 }
        };
Run Code Online (Sandbox Code Playgroud)

sim*_*que 5

对于你的榜样,您可以使用数据::别名别名%bar%foo.这允许您进行更改,%bar然后查看其中的更改%foo.

use strict;
use warnings;
use Data::Printer;
use Data::Alias;

my  %foo = ();
my  %bar = ();

alias %foo = %bar;

$bar{A}->{st} = 'a';
$bar{A}->{qt} = 'a';
$bar{B}->{st} = 'b';
$bar{B}->{qt} = 'b';

p %foo;
p %bar;
Run Code Online (Sandbox Code Playgroud)

输出:

{
    A   {
        qt   "a",
        st   "a"
    },
    B   {
        qt   "b",
        st   "b"
    }
}
{
    A   {
        qt   "a",
        st   "a"
    },
    B   {
        qt   "b",
        st   "b"
    }
}
Run Code Online (Sandbox Code Playgroud)