performance – 别名perl中的哈希元素

前端之家收集整理的这篇文章主要介绍了performance – 别名perl中的哈希元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以在不同的哈希键下访问相同的值?我如何告诉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

猜你在找的Perl相关文章