将哈希从一个包传递到另一个包中的方法并在 Perl 中操作它
我有两个包裹。一个包中有一个哈希值。我想将此哈希传递给另一个包中的方法,对其进行操作并查看前一个包中的结果。这是我的代码: {
package Statistical_Analysis;
use Moose;
our $data;
our $ref;
our $k;
our $v;
sub countUseCase
{
my ($self, $value, $hash) = @_;
print "Passed value: ".$value."\n";
print "Hash Address: ".$hash."\n";
$self->{ref} = $hash;
$self->{%$ref}{'country'} = "something";
#print "IP Address: ".$self->{data}."\n";
#print "Hash Value: ".$self->{ref{'ip_count'}}."\n";
}
}
{
package Parse;
use Moose;
our %ip_address;
sub getFields
{
our $stanalyze_obj = Statistical_Analysis->new();
my $ref = \%ip_address;
$stanalyze_obj->countUseCase($ref);
dispHashMap();
}
sub dispHashMap
{
print \%ip_address."\n";
while ( my ($k,$v) = each %ip_address )
{
print "$k => $v\n";
}
}
但我看不到哈希值的变化。有什么帮助吗?
I have two packages. There is one hash in one package. I want to pass this hash to a method in another package, manipulate it and see the results in the previous package. Here's my code:
{
package Statistical_Analysis;
use Moose;
our $data;
our $ref;
our $k;
our $v;
sub countUseCase
{
my ($self, $value, $hash) = @_;
print "Passed value: ".$value."\n";
print "Hash Address: ".$hash."\n";
$self->{ref} = $hash;
$self->{%$ref}{'country'} = "something";
#print "IP Address: ".$self->{data}."\n";
#print "Hash Value: ".$self->{ref{'ip_count'}}."\n";
}
}
{
package Parse;
use Moose;
our %ip_address;
sub getFields
{
our $stanalyze_obj = Statistical_Analysis->new();
my $ref = \%ip_address;
$stanalyze_obj->countUseCase($ref);
dispHashMap();
}
sub dispHashMap
{
print \%ip_address."\n";
while ( my ($k,$v) = each %ip_address )
{
print "$k => $v\n";
}
}
But I cant see the changes in the hash. Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你看不到任何变化,因为你从未改变它。因为它没有意义,我认为您打算在这样做时更改
$ip_address{country}
如果是这样,那应该是
当然,
$hash
存储在 < code>$self->{ref},所以您也可以使用可以缩写为
PS 的 which ,这些
our
变量是怎么回事?您几乎不必使用我们的
。@ISA
和@EXPORT_OK
是我能想到的唯一用途。所有这些都应该是我的
。PSS——实际上,这些几乎都不应该存在。声明你根本不使用的变量是怎么回事?这些声明之一是让你的错误变得不那么明显。
You don't see any change because you never change it. Since it makes no sense, I presume you meant to change the
$ip_address{country}
when you doIf so, that should be
Of course,
$hash
is stored in$self->{ref}
, so you could also usewhich can be shortened to
PS — What's with all the
our
variables? You should almost never have to useour
.@ISA
and@EXPORT_OK
are about the only uses I can think of. All of those should bemy
.PSS — Actually, almost none of those should exist at all. What's with declaring variables you don't even use? One of these declarations is making your error a lot less obvious.
您似乎只使用一个参数
$ref
调用了countUseCase
。仅使用一个参数调用该方法会导致$hash
变为 undef。It seems that you called
countUseCase
with only one parameter,$ref
. Calling that method with only one parameter, causes$hash
to be undef.