2011-08-09 34 views
6

Noob question here。我相信答案是創建對象,並將它們存儲在一個數組中,但我想看看是否有更簡單的方法。Perl - 對象數組

在JSON符號我可以像這樣創建對象的數組:

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

尼斯和簡單。沒有爭論。

我知道Perl不是JS,但有沒有更簡單的方法來複制一個對象數組,然後創建一個新的「類」,新的對象,並將它們推入一個數組?

我想什麼會使這成爲可能是JS提供的對象字面量類型符號。

或者,有沒有另一種方法來存儲兩個值,如上面?我想我可能只有兩個數組,每個數組都有標量值,但這看起來很醜陋......但比創建一個單獨的類以及所有這些廢話要容易得多。如果我正在編寫Java或其他東西,那麼沒問題,但我不想在編寫一個小腳本時煩惱所有這些。

+2

在JS ,對象與散列/關聯數組基本相同。在Perl中他們是不同的想法。如果你只是需要一些東西來放入數據,你不需要一個對象。對象是具有*行爲*的事物。 – hobbs

回答

15

這是一個開始。 @list數組的每個元素都是對帶有「寬度」和「高度」鍵的散列的引用。

#!/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"; 
} 
+0

然後你可以添加更多元素到數組中:'push @list,{width => 40,height => 70};'。 –

+1

+1用於嚴格使用;''使用警告;'。謝謝。 – L0j1k

3

散列的數組將做到這一點,像這樣

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

+1

更好的參考是http://perldoc.perl.org/perldsc.html – MkV

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 
      } 
     ); 

和所有的,缺少的只是