【问题标题】:Perl - Array of ObjectsPerl - 对象数组
【发布时间】:2011-08-10 15:27:01
【问题描述】:

这里是菜鸟问题。

我确定答案将是创建对象,并将它们存储在一个数组中,但我想看看是否有更简单的方法。

在 JSON 表示法中,我可以创建一个对象数组,如下所示:

[
  { width : 100, height : 50 },
  { width : 90, height : 30 },
  { width : 30, height : 10 }
]

漂亮而简单。不用争论。

我知道 Perl 不是 JS,但是有没有更简单的方法来复制一个对象数组,然后创建一个新的“类”,新的对象,并将它们推送到一个数组中?

我猜想使这成为可能的是 JS 提供的对象字面量类型表示法。

或者,有没有另一种方法来存储两个值,就像上面一样?我想我可以只有两个数组,每个数组都有标量值,但这看起来很丑……但比创建一个单独的类和所有这些废话要容易得多。如果我正在编写 Java 或其他东西,那没问题,但是当我只是编写一个小脚本时,我不想被所有这些困扰。

【问题讨论】:

  • 在 JS 中,对象与散列/关联数组基本相同。在 Perl 中,它们是不同的想法。如果你只需要一个东西来放数据,你就不需要一个对象。对象是具有行为的事物。

标签: perl


【解决方案1】:

这是一个开始。 @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 };.
【解决方案2】:

一个哈希数组可以做到这一点,像这样

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

【讨论】:

    【解决方案3】:

    与您在 JSON 中执行此操作的方式几乎相同,实际上,使用 JSONData::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
              }
            );
    

    而缺少的只是我的

    【讨论】:

      猜你喜欢
      • 2012-03-10
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      • 2016-10-18
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多