菜鸟问题在这里。
我确定答案是创建对象,并将它们存储在数组中,但我想看看是否有更简单的方法。
在 JSON 符号中,我可以创建一个对象数组,如下所示:
[
{ width : 100, height : 50 },
{ width : 90, height : 30 },
{ width : 30, height : 10 }
]
漂亮又简单。不用争论了。
我知道 Perl 不是 JS,但是有没有更简单的方法来复制一个对象数组,然后创建一个新的“类”,新的对象,并将它们放入一个数组中?
我想这可能是 JS 提供的对象字面量类型符号。
或者,是否有另一种存储两个值的方法,如上所示?我想我可以只有两个数组,每个数组都有标量值,但这看起来很难看……但比创建一个单独的类和所有这些废话要容易得多。如果我正在编写 Java 或其他东西,那没问题,但是当我只是在编写一个小脚本时,我不想被所有这些打扰。
这是一个开始。
@list
数组的每个元素都是对具有键“width”和“height”的散列的引用。
#!/usr/bin/perl
use strict;
use warnings;
my @list = (
{ width => 100, height => 50 },
{ width => 90, height => 30 },
{ width => 30, height => 10 }
);
foreach my $elem (@list) {
print "width=$elem->{width}, height=$elem->{height}\n";
}
然后您可以向数组添加更多元素:
push @list, { width => 40, height => 70 };
一个哈希数组就可以做到,像这样
my @file_attachments = (
{file => 'test1.zip', price => '10.00', desc => 'the 1st test'},
{file => 'test2.zip', price => '12.00', desc => 'the 2nd test'},
{file => 'test3.zip', price => '13.00', desc => 'the 3rd test'},
{file => 'test4.zip', price => '14.00', desc => 'the 4th test'}
);
然后像这样访问它
$file_attachments[0]{'file'}
有关更多信息,请查看此链接http://htmlfixit.com/cgi-tutes/tutorial_Perl_Primer_013_Advanced_data_constructs_An_array_of_hashes.php
与您在 JSON 中执行此操作的方式几乎相同,事实上,使用 JSON 和 Data::Dumper 模块从您的 JSON 中生成您可以在 Perl 代码中使用的输出:
use strict;
use warnings;
use JSON;
use Data::Dumper;
# correct key to "key"
my $json = <<'EOJSON';
[
{ "width" : 100, "height" : 50 },
{ "width" : 90, "height" : 30 },
{ "width" : 30, "height" : 10 }
]
EOJSON
my $data = decode_json($json);
print Data::Dumper->Dump([$data], ['*data']);
输出
@data = (
{
'width' => 100,
'height' => 50
},
{
'width' => 90,
'height' => 30
},
{
'width' => 30,
'height' => 10
}
);
所有缺少的是my