how access to hash which contains hash and sclar var?

Discussion in 'Perl Misc' started by kenneth, Dec 11, 2004.

  1. kenneth

    kenneth Guest

    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!
     
    kenneth, Dec 11, 2004
    #1
    1. Advertising

  2. kenneth wrote:
    > 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;

    --
    Gunnar Hjalmarsson
    Email: http://www.gunnar.cc/cgi-bin/contact.pl
     
    Gunnar Hjalmarsson, Dec 11, 2004
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. James Dyer
    Replies:
    5
    Views:
    688
  2. thomson
    Replies:
    10
    Views:
    2,529
    Eliyahu Goldin
    Jun 20, 2005
  3. thomson
    Replies:
    0
    Views:
    404
    thomson
    Jun 20, 2005
  4. Ed
    Replies:
    6
    Views:
    1,347
    =?ISO-8859-1?Q?Arne_Vajh=F8j?=
    Aug 2, 2007
  5. AddisLig
    Replies:
    0
    Views:
    329
    AddisLig
    Nov 16, 2008
Loading...

Share This Page