SPUG:Reference question

Richard Anderson richard at richard-anderson.org
Sun Mar 9 17:14:22 CST 2003


Hi Thane.  You quandary is another example of why almost every Perl program should start with:

#! /usr/bin/perl -w
use strict;

Adding this to your program and running makes it abort with the message:

Can't use string ("age") as a SCALAR ref while "strict refs" in use

when Perl executes the line:

print "$_ for $key is ${$_}\n";

You are attempting to treat $age as a scalar reference when it is just a scalar, not a reference.  The following code works:

#! /usr/local/bin/perl -w
use strict;
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};
    print "age for $key is $age\n";
    print "sex for $key is $sex\n";
}

-- 
Richard Anderson
richard at richard-anderson.org
www.richard-anderson.org
> 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};
> 
>     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";
> foreach ("age", "sex") {
>     print "$_ for $name is ${$_}\n";
> }
> And it works! What's the difference?
> Thanks in advance..
> _____________________________________________________________
> 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