无法将哈希作为模块中的引用传递

eni*_*osp 4 perl hash

我想将哈希引用传递给模块.但是,在模块中,我无法获得哈希值.

这个例子:

#!/usr/bin/perl
#code.pl
use strict;
use Module1;

my $obj = new Module1;

my %h = (
    k1 => 'V1'
);

print "reference on the caller", \%h, "\n";

my $y = $obj->printhash(\%h);
Run Code Online (Sandbox Code Playgroud)

现在,Module1.pm:

package Module1;
use strict;
use Exporter qw(import);
our @EXPORT_OK = qw();
use Data::Dumper;

sub new {
    my $class = $_[0];
    my $objref = {};
    bless $objref, $class;
    return $objref;
}


sub printhash {
    my $h = shift;

    print "reference on module -> $h \n";
    print "h on module -> ", Dumper $h, "\n";
}
1;
Run Code Online (Sandbox Code Playgroud)

输出将是这样的:

reference on the callerHASH(0x2df8528)
reference on module -> Module1=HASH(0x16a3f60)
h on module -> $VAR1 = bless( {}, 'Module1' );
$VAR2 = '
';
Run Code Online (Sandbox Code Playgroud)

如何获取调用者传递的值?这是perl的旧版本:v5.8.3

Que*_*tin 6

当您将sub作为方法调用时,第一个值@_将是您调用它的对象.

传递给它的第一个参数将是您当前忽略的第二个@_.

sub printhash {
    my ($self, $h) = @_;
Run Code Online (Sandbox Code Playgroud)


xxf*_*xxx 6

在Module1中,将子printhash更改为:

sub printhash {
    my ($self, $h) = @_;
    # leave the rest
}
Run Code Online (Sandbox Code Playgroud)

当您在对象上调用方法时$obj->method( $param1 ),方法将对象本身作为第一个参数,并将$ param1作为第二个参数.

perldoc perlootut - Perl教程中面向对象的编程

perldoc perlobj - Perl对象参考