Can one hash variable refer to another?

M

mrstevegross

I'm trying to figure out if one hash value can refer to another value
from the same hash. For instance:

my $hsh = {
a => 1,
b => $hsh->{a} };

print $hsh->{b}; # should print 1, but doesn't

Is there a way to make this work?

Thanks,
--Steve
 
J

J. Gleixner

mrstevegross said:
I'm trying to figure out if one hash value can refer to another value
from the same hash. For instance:

my $hsh = {
a => 1,
b => $hsh->{a} };

$hsh->{a} isn't defined yet.

If you had

use strict;

It would have given you an error.
print $hsh->{b}; # should print 1, but doesn't

Is there a way to make this work?

my $hsh;
$hsh->{ 'a' } = 1;
$hsh->{ 'b' } = $hsh->{ 'a' };
print $hsh->{b};
#fyi
$hsh->{ 'a' } = 4;
print $hsh->{b};
 
T

Tim McDaniel

$hsh->{a} isn't defined yet.

If you had

use strict;

It would have given you an error.

There's actually two problems with the code.

For one thing, it isn't declared yet. As "man perlsub" says, in the
"Private Variables via my()" section (in Perl 5.8.8, at least),

The declared variable is not introduced (is not visible) until after
the current statement. Thus,

my $x = $x;

can be used to initialize a new $x with the value of the old $x,
and the expression

my $x = 123 and $x == 123

is false unless the old $x happened to have the value 123.

That's why the error message under "use strict" is
Global symbol "$hsh" requires explicit package name at ...
$hsh isn't visible until after the semicolon in the quoted text
above.

If you declare $hsh in one statement, thus making it visible, and then
assign it in the next, as in

$ perl -w -e 'use strict;
my $hsh;
$hsh = {
a => 1,
b => $hsh->{a} };
print $hsh->{b}, "\n"'

it STILL doesn't work. Perl evaluates the entire right-hand side
before assigning the entire anonymous hash {...} value result to the
left-hand side. So $hsh->{a} gets evaluated, producing undef, before
$hsh is assigned to, giving element "a" a value. So the error message
under -w this time is

Use of uninitialized value in print at -e line 6.
 
D

Dr.Ruud

mrstevegross said:
I'm trying to figure out if one hash value can refer to another value
from the same hash. For instance:

my $hsh = {
a => 1,
b => $hsh->{a} };

print $hsh->{b}; # should print 1, but doesn't

Is there a way to make this work?

my $h;

$h = {
a => 1,
b => sub { $h->{a} },
};

my $val = $h->{ b };
$val = $val->() if ref $val eq "CODE";
print $val;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top