Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试在perl中打印混合哈希元素_Perl_Hash - Fatal编程技术网

尝试在perl中打印混合哈希元素

尝试在perl中打印混合哈希元素,perl,hash,Perl,Hash,我尝试以树的形式打印哈希键和值。下面给出了我的perl代码 use strict ; use warnings ; my %hash = ( first => { a => "one", b => "two", c => "three", }, second => { d => "four", e => "fiv

我尝试以树的形式打印哈希键和值。下面给出了我的perl代码

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";
    }
}
输出错误消息: 第二: d:四个 f:六个 e:五个 第三: 在C:\Users\Dell\Music\PerlPrac\prachish\hshofhsh\u net.pl第19行使用“strict refs”时,无法将字符串(“word”)用作哈希引用


这里,第三个键下的值不打印。我该怎么做?

您不能取消对字符串的引用(
$hash{third}
,即
word
)。您可以使用
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";
    }
}

因为
$hash{third}
的值不是hashref,所以
%{$hash{third}}
抛出了一个错误。您可以使用
if(ref$hash{$line}eq“hash”)…