SPUG:Reference question
Umar Cheema
umar at drizzle.com
Sun Mar 9 17:04:10 CST 2003
If you remove the "my" from the $age and $sex assignments, it works:
foreach my $key (keys %record) {
$age = $record{$key}{age};
$sex = $record{$key}{sex};
foreach ("age", "sex") {
print "$_ for $key is ${$_}\n";
}
}
I'd be curious to know why this works?
On Mon, 10 Mar 2003, Damian Conway wrote:
> 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
>
> _____________________________________________________________
> Seattle Perl Users Group Mailing List
> POST TO: spug-list at mail.pm.org
> ACCOUNT CONFIG: http://mail.pm.org/mailman/listinfo/spug-list
> MEETINGS: 3rd Tuesdays, U-District, Seattle WA
> WEB PAGE: www.seattleperl.org
>
More information about the spug-list
mailing list