首页 > 解决方案 > 如何在 perl 类中正确使用哈希

问题描述

我学会了创建一个像这样的新类,将哈希作为实例化的一部分:

sub new {
    my $class = shift;
    my( $response, $config ) = @_;

    my $self = {
       _response => $response
       _config => $config
    };

    bless $self, $class;
    return $self;
}

sub getConfig {
  my( $self ) = @_;
  return $self->{_config};
}

sub getResponse {
  my( $self ) = @_;
  return $self->{_response};
}

当我创建类时,我会在实例化时向它发送一些配置。


my $response = {
  "my" => "response"
}

my $config = {
  "my" => "config"
}

$inst = MyClass::Class->new($response, $config);

当我得到这些信息时,它似乎工作正常。

Data::Dumper

print Dumper $insta->getConfig();

$VAR = {
  "my" => "config"
}

现在事实证明,我得到的配置哈希看起来像这样:

%R_CONFIG = (
   "my", "config"
);

当我把它放到我的代码库中时,一切都变得松散了:

$inst = Class->new($response, %config);

我显然犯了一些根本性的错误。而且我似乎无法从调试中得到任何可靠的信息,因为例如,当我使用 say 时,一切仍然在说它是一个哈希ref()

在创建此类时,我在哈希方面犯了什么错误?

标签: perl

解决方案


您只能将标量传递给 subs。

$inst = Class->new($response, %config);

是相同的

$inst = Class->new($response, "my", "config");

您的方法需要对哈希的引用,因此您应该使用

$inst = Class->new($response, \%config);

推荐阅读