how access to hash which contains hash and sclar var?

K

kenneth

hi
i'd like to access to hash which contains hash and sclar var,and failed.
access to hash of hash is ok, i find that in <<Programming Perl>>.
use the code below:
for my $family ( keys %test ) {
print "$family: \n";
for my $role ( keys %{ $test{$family} } ) {
print "$role=$test{$family}{$role} ";
}
print "\n";

}
but now i construct a structure use below codes:
my %test=(
number => "20",
);

$test{"homepage"}{"index.html"}=21;
$test{"homepage"}{"index.php"}=2;
and the above code failed to access to the element of the structure with
error of "Can't use string ("20") as a HASH ref while "strict refs" in
use at hash_of_hash.pl line 26.
shell returned 255"
any advises? thank you!
 
G

Gunnar Hjalmarsson

kenneth said:
i'd like to access to hash which contains hash and sclar var,and failed.
access to hash of hash is ok, i find that in <<Programming Perl>>.
use the code below:
for my $family ( keys %test ) {
print "$family: \n";
for my $role ( keys %{ $test{$family} } ) {
print "$role=$test{$family}{$role} ";
}
print "\n";

}
but now i construct a structure use below codes:
my %test=(
number => "20",
);

$test{"homepage"}{"index.html"}=21;
$test{"homepage"}{"index.php"}=2;
and the above code failed to access to the element of the structure with
error of "Can't use string ("20") as a HASH ref ...

You need to check whether respective key is a reference. Something like:

for my $key ( keys %test ) {
print "$key: \n";
if ( ref $test{$key} ) {
for ( keys %{ $test{$key} } ) {
print "$_=$test{$key}{$_} ";
}
} else {
print $test{$key};
}
print "\n";
}

You may also want to use this convenient method to print a complex data
structure:

use Data::Dumper;
print Dumper \%test;
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top