2010-11-08 39 views
2

我有一個實例變量,屬性,一個被定義和實例,像這樣:Perl的愁楚 - 分配並返回一個哈希

$self->{properties}{$key1} = $value; 

我的理解,這將宣告屬性字段,並且也將其設置爲一個Hash基元,包含一個鍵值對。

我試圖寫的特性實例變量一個getter,將返回哈希:

sub getProperties{ 
    my $self = shift; 

    my %myhash = $self->{properties}; 
    return %myhash; 
} 

而且隨後致電像這樣,吸氣:

my %properties = $properties->getProperties(); 

當我嘗試編譯我得到:

"Odd number of elements in hash assignment at 70..." 

line 70 being: my %myhash = $self->{properties}; 

回答

7

在這行代碼:

my %myhash = $self->{properties}; 

%myhash是一個散列,而$ self - > {properties}是散列引用。所以你有效地返回一個帶有一個鍵/值對的散列,其中鍵是對散列的引用並且值是undef。

如果你真的想返回的哈希,這樣做:

my %myhash = %{$self->{properties}}; 

或者,返回一個哈希引用。這通常比返回一個散列更可取,因爲它不會創建原始散列的副本,因此隨着散列變大,內存效率會更高。下面是它的外觀:

sub getProperties { 
    my $self = shift; 
    return $self->{properties}; 
} 

然後在你的調用代碼,而不是這樣的:

my %properties = $properties->getProperties(); 
$somevalue = $properties{'somekey'}; 

做到這一點:

# getProperties returns a reference, so assign to a scalar 
# variable ($foo) rather than a hash (%foo) 
my $properties = $properties->getProperties(); 

# Use -> notation to dereference the hash reference 
$somevalue = $properties->{'somekey'}; 
+0

非常感謝西蒙 – 2010-11-08 23:24:27

+0

不客氣灰 - 好運與你的Perl! :) – 2010-11-08 23:29:11

+0

西蒙,如果我返回像你說的哈希引用 - 我可以通過這樣做後來得到一個哈希引用? my%associations =%{$ properties-> getProperties()}; – 2010-11-08 23:49:56

2

不是$self->{properties}一個hashref不是哈希?

$ perl t4.pl 
size -> 42 

t4.pl

#!/usr/bin.perl 
use strict; 
use warnings; 

use t4; 

my $t4 = t4->new(); 
my %hash = $t4->getProperties(); 
for my $key (keys %hash) { 
    print "$key -> $hash{$key}\n"; 
} 

t4.pm

package t4; 

sub new { 
    my $class = shift; 
    my $self = {}; 
    $self->{properties}{size} = 42; 
    bless ($self, $class); 
} 

sub getProperties { 
    my $self = shift; 
    my %myhash = %{$self->{properties}}; 
    return %myhash; 
} 

1; 
+0

感謝redgritty – 2010-11-08 23:24:44