-6

我是 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”。如上所述,我可以将此字符串用作创建的文件名。我无法更改上述哈希结构。它就在那里,由其他人创建,我只能访问它。

谢谢

4

1 回答 1

0

给定以下代码:

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}
于 2015-11-19T04:12:43.733 回答