0

是否可以强制不同的 perl 哈希键映射到相同的值?例如:

my %h = (
   aaa => 'val_1',
   bbb => 'val_2',
);
print "==============\n";
&dump();

$h{bbb} = \$h{aaa};    
&dump();

$h{aaa} = 'new';    
&dump();

sub dump{
    foreach my $k ( sort keys %h ){
    print "$k => $h{$k}\n";
    }
    print "==============\n";
}

这将打印:

==============
aaa => val_1
bbb => val_2
==============
aaa => val_1
bbb => SCALAR(0x801d48)
==============
aaa => new
bbb => SCALAR(0x801d48)

但我想要的是:

==============
aaa => val_1
bbb => val_2
==============
aaa => val_1
bbb => val_1
==============
aaa => new
bbb => new
4

4 回答 4

2

您可以存储对值的引用而不是值(如您所示)。这是做到这一点的“干净”方式。

正如 clintp 建议的那样,不太干净的方法是使用绑定哈希。

不太干净的方法是别名:

use Data::Alias;
...
alias $h{bbb} = $h{aaa};

请注意,这涉及到 perl 的内部结构,如果 Data::Alias 变得无人维护并且新的 perl 版本破坏了它,这会带来一定程度的风险。

于 2013-01-15T17:13:36.077 回答
0
#!\usr\bin\perl 
use strict;
use warnings;

my %h = (
   aaa => 'val_1',
   bbb => 'val_2',
);
print "==============\n";
&dump();

$h{bbb} = $h{aaa};    
&dump();

$h{aaa} = 'new';    
$h{bbb} = $h{aaa};
&dump();

sub dump{
    foreach my $k ( sort keys %h ){
    print "$k => $h{$k}\n";
    }
    print "==============\n";
}

输出是:

==============
aaa => val_1
bbb => val_2
==============
aaa => val_1
bbb => val_1
==============
aaa => new
bbb => new
于 2013-01-30T06:53:19.637 回答
0

或者你可以这样做,这将给出你想要的输出:

#!\usr\bin\perl 
use strict;
use warnings;
my %h = (aaa => 'val_1', bbb => 'val_2');
print "==============\n";
&dump();
my $ha = \$h{aaa}; 
$h{bbb} = $$ha;
&dump();
$$ha = 'new'; 
$h{bbb} = $$ha;   
&dump();
sub dump
{
 foreach my $k (sort keys %h)
 {
  print "$k => $h{$k}\n";
 }
 print "==============\n";
}
于 2013-01-31T05:24:56.373 回答
0

您可以使用tie创建一个哈希实现,该实现将在您检索值时执行自动取消引用。

于 2013-01-15T16:39:03.060 回答