在Perl中打印数组哈希散列的有效方法

tjw*_*992 1 perl hash data-structures

我正在编写一个脚本,涉及打印数组散列的哈希内容.

ex(伪代码):

my %hash = ();
$hash{key1}{key2} = ['value1', 'value2', 'value3', . . .];
Run Code Online (Sandbox Code Playgroud)

要么

$hash{key1}{key2} = @array_of_values;
Run Code Online (Sandbox Code Playgroud)

基本上我希望能够为任意数量的键组合执行此操作,并能够循环遍历所有可能的键/值对(或者可能更正确地表示为键,键/数组对,因为每个值实际上是一个数组值和每个数组有2个与之关联的键)并以下列格式打印输出:

"key1,key2,value1,value2,value3,... \n"

例如:

#!/usr/bin/perl

use strict;
use warnings;

# initialize hash
my %hash = ();
my $string1 = "string1";
my $string2 = "string2";

# push strings onto arrays stored in hash
push @{$hash{a}{b}}, $string1;
push @{$hash{a}{b}}, $string2;
push @{$hash{c}{d}}, $string2;
push @{$hash{c}{d}}, $string1;

# print elements of hash
# (want to do this as a loop for all possible key/value pairs)
local $, = ',';
print "a, b, ";
print @{$hash{a}{b}};
print "\n";
print "c, d, ";
print @{$hash{c}{d}};
print "\n";

system ('pause');
Run Code Online (Sandbox Code Playgroud)

此代码的输出如下所示:

a, b, string1,string2
c, d, string2,string1
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)

我正在考虑使用each操作符,但它似乎只适用于一维哈希.(each只返回一个键值对,当涉及2个键时它无法正常工作)

我如何简化此代码以遍历循环中的散列并打印所需的输出,无论我的散列有多大?

TLP*_*TLP 5

each即使对于多级哈希,使用的工作也很完美,你只需要确保参数是一个哈希.这是一个如何做到这一点的例子.我还展示了如何初始化你的哈希值.

use strict;
use warnings;
use v5.14;

my $string1 = "string1";
my $string2 = "string2";
my %hash = (
    a => { 
        b => [ $string1, $string2 ],
    },
    c => {
        d => [ $string2, $string1 ],
    }
);

for my $key (keys %hash) {
    while (my ($k, $v) = each %{ $hash{$key} }) {
        say join ", ", $key, $k, @$v;
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

c, d, string2, string1
a, b, string1, string2
Run Code Online (Sandbox Code Playgroud)

注意使用@$v到内部数组的简单性,而不是有点麻烦的替代方案@{ $hash{$key}{$k} }.