Perl - 对象数组 [英] Perl - Array of Objects
问题描述
菜鸟问题在这里.
我确定答案是创建对象,并将它们存储在数组中,但我想看看是否有更简单的方法.
在 JSON 符号中,我可以像这样创建一个对象数组:
<预><代码>[{宽度:100,高度:50},{宽度:90,高度:30},{宽度:30,高度:10}]很好很简单.没有争论.
我知道 Perl 不是 JS,但是有没有更简单的方法来复制对象数组,然后创建一个新的类",新建对象,并将它们推送到数组中?
我想使这成为可能的是 JS 提供的对象字面量类型符号.
或者,有没有另一种方法来存储两个值,就像上面一样?我想我可以只有两个数组,每个数组都有标量值,但这看起来很丑……但比创建一个单独的类要容易得多,而且所有这些废话.如果我正在编写 Java 或其他东西,那么没问题,但是当我只是编写一个小脚本时,我不想被所有这些打扰.
这是一个开始.@list
数组的每个元素都是对具有键width"和height"的散列的引用.
#!/usr/bin/perl使用严格;使用警告;我的@list = ({ 宽度 =>100,高度=>50 },{ 宽度 =>90,高度=>30 },{ 宽度 =>30,高度=>10 });foreach 我的 $elem (@list) {打印 "width=$elem->{width}, height=$elem->{height}\n";}
Noob question here.
I'm sure the answer will be create objects, and store them in an array, but I want to see if there is an easier way.
In JSON notation I can create an array of objects like so:
[
{ width : 100, height : 50 },
{ width : 90, height : 30 },
{ width : 30, height : 10 }
]
Nice and simple. No arguing that.
I know Perl is not JS, but is there an easier way to duplicate an array of objects, then to create a new "class", new the objects, and push them in an array?
I guess what would make this possible is an object literal type notation that JS provides.
Or, is there another way to store two values, like above? I guess I could just have two arrays, each with scalar values, but that seems ugly...but much easier than creating a separate class, and all that crap. If I were writing Java or something, then no problem, but I don't want to be bothered with all that when I'm just writing a small script.
Here's a start. Each element of the @list
array is a reference to a hash with keys "width" and "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";
}
这篇关于Perl - 对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!