perl - 如何在 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()
。
在创建此类时,我在哈希方面犯了什么错误?
解决方案
您只能将标量传递给 subs。
$inst = Class->new($response, %config);
是相同的
$inst = Class->new($response, "my", "config");
您的方法需要对哈希的引用,因此您应该使用
$inst = Class->new($response, \%config);
推荐阅读
- python - 无法从 pytest.fixture 获取数据,而是获取数据位置
- sql - 如何获得前三行的总和,然后是新列中的下三行
- c# - html解析器。加载文件或程序集失败
- prestashop - 我想要另一张图片,而不是封面图片产品
- module - 如何更改yii2默认模块
- javascript - 将复选框传递给隐藏的输入
- haskell - 第一个代码示例中的“Get Programming With Haskell”错误
- android - Nativescript-Camera 拍照后不显示刻度或交叉
- ios - 如何在 UIDocumentInteractionController 中使用 AirDrop 发送大文件
- get - 无需 API 从 Vimeo 获取 img 缩略图