如何在Perl中打印嵌套哈希值?

dnph8jn4  于 2022-11-15  发布在  Perl
关注(0)|答案(3)|浏览(201)
$dict{'one'}=1;
print %dict;

这将打印
一个1
但是如果我的代码在字典哈希中有一个字典哈希,如下所示:

my %dict;
$dict{'1'}{'1'}=2;

print %dict;

输出如下:

1HASH(0xb1db78)

即使我把最后一行改成

print $dict{'1'};

输出为:
散列(0x13ccb78)
如何获取字典哈希的内容而不是引用位置?

2vuwiymt

2vuwiymt1#

如果你想要整个结构,使用核心Data::Dumper模块。

use strict;
use warnings;

use Data::Dumper;

my %hash;
$hash{1}{1} = 2;

print Dumper( \%hash );

输出:

$VAR1 = {
          '1' => {
                   '1' => 2
                 }
        };

如果你想在Perl中使用嵌套结构(超越任何琐碎的事情),你需要学习 references。如果你熟悉指针,那么你已经完成了一半。
最好的资源在官方文档中:

4zcjmb1e

4zcjmb1e2#

这是错误的
它应该是$dict{'one'}=1;
您应该拥有类似下面的内容。警告:这是未经测试的代码,但你明白我想说的:

#!/usr/bin/perl -w

use strict;
use Data::Dumper;

my %dict;
$dict{'1'}{'1'}=2;
$dict{'2'}{'2'}=3;

#print Dumper(\%dict);

foreach my $keys ( keys %dict )
{
    print "$keys : ";
    foreach my $keys2 ( keys %{ $dict{keys} } )
    {
        print "$keys2 = $dict{keys}{$keys2} \n" ;
    }
    print "\n";
}
cedebl8k

cedebl8k3#

这是我的解决方案。您可以浏览hasharrayhash + array

#!/usr/bin/perl

%foo = (
    flintstones => { 
        husband => "fred", 
        pal => "barney", 
    }, 
    jetsons => { 
        husband => [ 
            11, 
            { 
                aa => 100, 
                bb => [ 200, 201, 202 ], 
                cc => 300 
            }, 
            33 
        ], 
        wife => "jane", 
        "his boy" => "elroy",
    }, 
    simpsons => { 
        husband => "homer", 
        wife => "marge", 
        kid => "bart", 
    },
);

sub walk_hash {
    my ($hash, $name) = @_;
    while (my ($key, $value) = each (%{$hash}))
    {
        if (ref $value eq 'HASH') {
            walk_hash($value, $name . "{" . $key . "}");
        } elsif (ref $value eq 'ARRAY') {
            walk_array($value, $name . "{" . $key . "}");
        } else {
            print $name . "{" . $key . "} = $value\n";
        }
    }
}

sub walk_array {
    my ($array, $name) = @_;
    for (my $i = 0; $i <= $#{$array}; $i++)
    {
        if (ref $$array[$i] eq 'HASH') {
            walk_hash($$array[$i], $name . "[" . $i . "]");
        } elsif (ref $$array[$i] eq 'ARRAY') {
            walk_array($$array[$i], $name . "[" . $i . "]");
        } else {
            print $name . "[" . $i . "] = $$array[$i]\n";
        }
    }
}

walk_hash(\%foo, '%foo');

输出:

bash$ ./test.pl 
%foo{flintstones}{pal} = barney
%foo{flintstones}{husband} = fred
%foo{jetsons}{his boy} = elroy
%foo{jetsons}{wife} = jane
%foo{jetsons}{husband}[0] = 11
%foo{jetsons}{husband}[1]{aa} = 100
%foo{jetsons}{husband}[1]{bb}[0] = 200
%foo{jetsons}{husband}[1]{bb}[1] = 201
%foo{jetsons}{husband}[1]{bb}[2] = 202
%foo{jetsons}{husband}[1]{cc} = 300
%foo{jetsons}{husband}[2] = 33
%foo{simpsons}{kid} = bart
%foo{simpsons}{husband} = homer
%foo{simpsons}{wife} = marge

相关问题