繁体   English   中英

从 perl 中的散列打印数组值

[英]Printing array value from a hash in perl

我是 perl 的新手,这件事让我发疯。 我有一个哈希如下

%temp = (
  a_collection => [\%first, \%second]
)

我想将数组元素作为字符串取出,以便我可以将它们用作循环中的参数。 我有以下代码

foreach $item (@{$temp{'a_collection'}})
{
  <convert to json> $item  #convert each of the above hash to a json blob
  <write to file> $file    #write first blob to file "first.json" and so on
}

我得到了转换为 json 的部分。 我可以将它打印到标准输出。 现在我想把它写到一个文件中。 这里 $file 应该有名称“first”和“second”。 因此,循环将创建两个文件,其中包含上述哈希中存在的哈希变量的名称。 我希望文件名匹配,以便我可以跟踪创建的内容。

编辑:基本前提很简单。 无论我做什么,无论是 json 编码等,我都希望将哈希变量名称作为字符串。 所以在上面的数组中,我可以有一个任何名称\\%somename 的散列,在循环中我想要不同变量中的实际字符串“somename”。 如上所述,我可以将此字符串用作创建的文件名。 我无法更改上述哈希结构。 它就在那里,由其他人创建,我只能访问它。

谢谢

鉴于以下代码:

use strict;
use warnings;

my %first  = (foo => 2, bar => 3, bat => 5);
my %second = (baz => 7, quux => 11);
my %temp   = (a_collection => [\%first, \%second]);

for my $href (@{$temp{a_collection}}) {
    for my $key (keys(%$href)) {
        print "$key: $href->{$key}\n";
    }
}

这是产生的输出:

bar: 3
foo: 2
bat: 5
quux: 11
baz: 7

提供新信息后编辑:

my %first  = (foo => 2, bar => 3, bat => 5);
my %second = (baz => 7, quux => 11);
my %temp   = (first => \%first, second => \%second);

for my $key (keys(%temp)) {
    print "$key\n";
}

在提供更多新信息后进行编辑:

use JSON::XS;

my %first  = (foo => 2, bar => 3, bat => 5);
my %second = (baz => 7, quux => 11);
my %temp   = (first => \%first, second => \%second);

for my $key (keys(%temp)) {
    open(my $fh, '>', "$key.json") or die $!;
    print $fh encode_json($temp{$key});
    close($fh);
}

first.json内容:

{"foo":2,"bat":5,"bar":3}

second.json内容:

{"quux":11,"baz":7}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM