开发者

Passing hashes from a package to a method in another package and manipulating it in Perl

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?


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 do

 $self->{%$ref}{'country'} = 'something';

If so, that should be

 $hash->{country} = 'something';

Of course, $hash is stored in $self->{ref}, so you could also use

 $self->{ref}->{country} = 'something';

which can be shortened to

 $self->{ref}{country} = 'something';

PS — What's with all the our variables? You should almost never have to use our. @ISA and @EXPORT_OK are about the only uses I can think of. All of those should be my.

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.


It seems that you called countUseCase with only one parameter, $ref. Calling that method with only one parameter, causes $hash to be undef.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜