SPUG:Reference question

Thane Williams thane at fastmail.fm
Sun Mar 9 18:54:08 CST 2003


Thanks for the answers.

On Mon, 10 Mar 2003 09:52:56 +1100, "Damian Conway" <damian at conway.org>
said:
> Thane Williams wrote:
> 
> > Ok, maybe someone can point out the obvious to me here. Here's my code:
> > 
> > #!/usr/bin/perl
> > my %record
> > $record{Wilma}{age} = 32;
> > $record{Fred}{age} = 38;
> > $record{Wilma}{sex} = "female";
> > $record{Fred}{sex} = "male";
> > 
> > foreach my $key (keys %record) {
> >     my $age = $record{$key}{age};
> >     my $sex = $record{$key}{sex};
> 
> Lexical scalars used.
> 
> > 
> >     foreach ("age", "sex") {
> >         print "$_ for $key is ${$_}\n";
> >     }
> > }
> > 
> > The foreach loop prints this:
> > age for Fred is
> > sex for Fred is
> > age for Wilma is
> > sex for Wilma is
> > 
> > If $_ equals "age", I'd expect ${$_} to equal $age.. which it apparently
> > doesn't. (I get the same results even if I put "my $age = 50;").
> > 
> > I tried this test code:
> > 
> > #!/usr/bin/perl
> > $name = "Fred";
> > $age = "55";
> > $sex = "male";
> 
> Package scalars used.
> 
> > foreach ("age", "sex") {
> >     print "$_ for $name is ${$_}\n";
> > }  
> > And it works! What's the difference?
> 
> ${$_} is ${"name"} or ${"age"}.
> These are symbolic dereferences.
> Symbolic dereferences always end up at a package variable, never a
> lexical.
> 
> HTH,
> 
> Damian
> 
> 



More information about the spug-list mailing list