perl - 在 Perl 中打印数组哈希的有效方法

标签 perl data-structures hash

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

ex(伪代码):

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

$hash{key1}{key2} = @array_of_values;

基本上,我希望能够对任意数量的键组合执行此操作,并能够遍历所有可能的键/值对(或者可能更正确地表述为键、键/数组对,因为每个值实际上是一个值数组,每个数组有 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');

这段代码的输出如下所示:

a, b, string1,string2
c, d, string2,string1
Press any key to continue . . .

我正在考虑使用 each 运算符,但它似乎只适用于一维哈希。 (each只返回一对键值对,涉及2个键时不能正常工作)

无论我的哈希有多大,我如何简化这段代码以循环遍历哈希并打印所需的输出?

最佳答案

使用 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;
    }
}

输出:

c, d, string2, string1
a, b, string1, string2

请注意使用 @$v 获取最内层数组的简单性,而不是使用有点麻烦的替代方法 @{ $hash{$key}{$k} } .

关于perl - 在 Perl 中打印数组哈希的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25767983/

相关文章:

algorithm - 有向图行走 - 至少访问每个节点一次

c++ - 智能指针和unordered_map,unordered_set等

Eclipse IDE - 背景色

c++ - 自定义数据类型是否是可变大小效率的可能且可行的选择?

perl - perl 中 "\c"的用途是什么?

c - 我的程序意外停止工作

arrays - Perl:哈希中的数字排序数组

php - 从 Level3 CDN 保护 RT​​MP 流的问题

php - 在 mysql 中组织更改字段值

Perl Image::Resize 模块和 PNG 图像