在一个模块中无法获取作为引用传递的哈希值

4

我希望将哈希引用传递给一个模块,但是在模块中,我无法获得哈希的返回值。

示例:

#!/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);

现在,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;

输出结果将类似于:
reference on the callerHASH(0x2df8528)
reference on module -> Module1=HASH(0x16a3f60)
h on module -> $VAR1 = bless( {}, 'Module1' );
$VAR2 = '
';

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


1
你不应该在面向对象的模块中使用 Exporter。只需删除 use Exporterour @EXPORT_OK 即可。 - Borodin
2个回答

6
当您将子程序作为方法调用时,@_中的第一个值将是您调用它的对象。
您传递给它的第一个参数将成为@_中的第二个值,目前您正在忽略它。
sub printhash {
    my ($self, $h) = @_;

6
在Module1中,将sub printhash更改为:
sub printhash {
    my ($self, $h) = @_;
    # leave the rest
}

当你调用一个对象的方法时,例如 $obj->method( $param1 ) ,该方法将对象本身作为第一个参数,并将 $param1 作为第二个参数。 perldoc perlootut - Perl教程中面向对象编程部分。 perldoc perlobj - Perl对象引用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接