Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'};
like image 695
key_ Avatar asked Dec 09 '22 21:12

key_


2 Answers

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
like image 104
ikegami Avatar answered Dec 27 '22 02:12

ikegami


Tie::AliasHash will work, though I wouldn't reccommend going this route. What are you trying to do that you feel you need to alias hash keys? There's likely a better route to go.

like image 38
Oesor Avatar answered Dec 27 '22 00:12

Oesor