2010-04-24 41 views
4

我只是用Perl初學者,所以如果這聽起來愚蠢的 - 對不起爲:)如何在Perl構造器中定義一個空數組?

我的問題是 - 我試圖寫一個類,它有一個空的陣列,在類的構造函數中定義。所以我是這樣做的:

package MyClass; 

use strict; 

sub new { 
    my ($C) = @_; 
    my $self = { 
     items =>() 
    }; 
    bless $self, ref $C || $C; 
} 

sub get { 
    return $_[0]->{items}; 
} 

1; 

後來我測試我的類簡單的腳本:

use strict; 
use Data::Dumper; 
use MyClass; 

my $o = MyClass->new(); 
my @items = $o->get(); 

print "length = ", scalar(@items), "\n", Dumper(@items); 

,當運行腳本,我得到以下幾點:

$ perl my_test.pl 
length = 1 
$VAR1 = undef; 

爲什麼我我做錯了什麼導致我得到我的items陣列充滿undef

也許有人可以告訴我怎麼樣的類需要定義,所以我不會得到我的數組中的任何默認值?

回答

10

匿名數組引用構造函數是[]而不是()它用於將語句組合到列表中。在這種情況下,()變爲空白列表,並且perl看到my $self = { item => };。如果您使用use warnings;運行,您會收到關於該消息的消息。

而且,在你get子程序,你可能會想提領你的領域爲參考的返回列表,而不是到數組:

sub get { 
    return @{ $_[0]->{items} }; 
} 
+0

謝謝!現在一切正常 – Laimoncijus 2010-04-25 07:03:14

相關問題