key*_*ey_ 3 perl performance alias reference copy-on-write
是否可以在不同的哈希键下访问相同的值?我如何告诉Perl不要复制"非常长的文本?"
$hash->{'key'} = 'very long text';
$hash->{'alias'} = $hash->{'key'};
Run Code Online (Sandbox Code Playgroud)
简单的方法是使用对公共变量的引用.
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
Run Code Online (Sandbox Code Playgroud)
复杂的方法是使用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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1215 次 |
| 最近记录: |