3
votes

I try to print hash key and value in tree form. my perl code is given below.

use strict ;
use warnings ;
my %hash = (
    first => {
            a => "one",
            b => "two",
            c => "three",
    },
    second => {
            d => "four",
            e => "five",
            f => "six",
    },
    third => "word",
);

foreach my $line (keys %hash) {
    print "$line: \n";
    foreach my $elem (keys %{$hash{$line}}) {
        print "  $elem: " . $hash{$line}->{$elem} . "\n";
    }
}

output error message: second: d: four f: six e: five third: Can't use string ("word") as a HASH ref while "strict refs" in use at C:\Users\Dell\Music\PerlPrac\pracHash\hshofhsh_net.pl line 19.

here, under third key value not print. how can i do it?

1
Because the value of $hash{third} is not a hashref, so %{$hash{third}} is throwing an error. You can use if (ref $hash{$line} eq "HASH") ... - glenn jackman

1 Answers

4
votes

You can't dereference a string ($hash{third}, i.e. word). You can test whether a particular scalar is a reference or not using ref:

for my $line (keys %hash) {
    print "$line: \n";
    if ('HASH' eq ref $hash{$line}) {
        for my $elem (keys %{ $hash{$line} }) {
            print "  $elem: $hash{$line}{$elem}\n";
        }
    } else {
        print "  $hash{$line}\n";
    }
}