gpt4 book ai didi

perl - 无法获取作为模块中引用传递的哈希值

转载 作者:行者123 更新时间:2023-12-02 03:28:02 24 4
gpt4 key购买 nike

我想将哈希引用传递给模块。但是,在模块中,我无法取回哈希值。

示例:

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

最佳答案

在 Module1 中,将 sub printhash 更改为:

sub printhash {
my ($self, $h) = @_;
# leave the rest
}

当您以 $obj->method( $param1 ) 的形式调用对象上的方法时方法获取对象本身作为第一个参数,$param1 作为第二个参数。

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

perldoc perlobj - Perl 对象引用

关于perl - 无法获取作为模块中引用传递的哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37481027/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com