Perl困境 - 分配和返回哈希

chi*_*uit 2 perl

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

 $self->{properties}{$key1} = $value;
Run Code Online (Sandbox Code Playgroud)

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

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

sub getProperties{
    my $self = shift;

    my %myhash = $self->{properties}; 
    return %myhash;
}
Run Code Online (Sandbox Code Playgroud)

然后像这样调用getter:

my %properties = $properties->getProperties();
Run Code Online (Sandbox Code Playgroud)

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

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

line 70 being:    my %myhash = $self->{properties}; 
Run Code Online (Sandbox Code Playgroud)

Sim*_*ker 7

在这行代码中:

my %myhash = $self->{properties};
Run Code Online (Sandbox Code Playgroud)

%myhash是一个哈希,而$ self - > {properties}是一个哈希引用.所以你有效地返回一个带有一个键/值对的散列,其中键是对散列的引用,值是undef.

如果您确实想要返回哈希,请执行以下操作:

my %myhash = %{$self->{properties}};
Run Code Online (Sandbox Code Playgroud)

或者,返回哈希引用.这通常比返回哈希更可取,因为它不会复制原始哈希,因此随着哈希变大,内存效率会更高.以下是它的外观:

sub getProperties {
    my $self = shift;
    return $self->{properties};
}
Run Code Online (Sandbox Code Playgroud)

然后在你的调用代码而不是这个:

my %properties = $properties->getProperties();
$somevalue = $properties{'somekey'};
Run Code Online (Sandbox Code Playgroud)

做这个:

# 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'};
Run Code Online (Sandbox Code Playgroud)