Perl困境 - 分配和返回哈希

时间:2010-11-08 23:08:04

标签: perl

我有一个实例变量,属性,正在声明和实例化,如下所示:

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

我理解这将声明属性字段,并将其设置为包含一个键值对的Hash原语。

我正在尝试为属性实例变量编写一个getter,它将返回哈希:

sub getProperties{
    my $self = shift;

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

然后像这样调用getter:

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

当我尝试编译时,我得到:

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

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

2 个答案:

答案 0 :(得分: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'};

答案 1 :(得分: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;