performanceperlreferencealiascopy-on-write

alias a hash element in perl


Is it possible to access the same value under different hash keys? How can I tell Perl not to copy the "very long text?"

$hash->{'key'} = 'very long text';
$hash->{'alias'} = $hash->{'key'};

Solution

  • The simple way is to use a reference to a common variable.

    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
    

    The complicated way is to use 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