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'};
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With