是否可以在不同的哈希键下访问相同的值?我如何告诉Perl不要复制“非常长的文本?”
$hash->{'key'} = 'very long text'; $hash->{'alias'} = $hash->{'key'};
解决方法
简单的方法是使用对公共变量的引用.
my $hash; my $val = 'very long text'; $hash->{key} = \$val; $hash->{alias} = $hash->{key}; say ${ $hash->{key} }; # very long text say ${ $hash->{alias} }; # very long text ${ $hash->{key} } = 'some other very long text'; say ${ $hash->{key} }; # some other very long text say ${ $hash->{alias} }; # some other very long text say $hash->{key} == $hash->{alias} ? 1 : 0; # 1
复杂的方法是使用Data::Alias.
use Data::Alias qw( alias ); my $hash; $hash->{key} = 'very long text'; alias $hash->{alias} = $hash->{key}; say $hash->{key}; # very long text say $hash->{alias}; # very long text $hash->{key} = 'some other very long text'; say $hash->{key}; # some other very long text say $hash->{alias}; # some other very long text say \$hash->{key} == \$hash->{alias} ? 1 : 0; # 1