我正在创建一个具有基类的子类Net::SSH2
.当我试图添加一个类变量时,我收到错误说 -
不是F:\ temp\fooA.pl第17行的HASH引用.
如果我做同样的事情Net::SSH2
那么它工作正常.
这是代码:
use strict;
my $x = Foo->new();
package Foo;
use base qw (Net::SSH2);
sub new {
my ($class, %args) = @_;
my $self = $class->SUPER::new(%args);
$self->{'key'} = 'value';
bless $self, $class;
return $self;
}
Run Code Online (Sandbox Code Playgroud)
这很简单:Net :: SSH2不返回散列引用,但是一个有福的标量:
use Scalar::Util qw(reftype);
print reftype($self) . "\n"; # SCALAR
Run Code Online (Sandbox Code Playgroud)
顺便说一句:依赖第三方代码的实现细节总是很危险的.
一种可能的解决方案是使用内外对象:
package Foo;
use Scalar::Util qw( refaddr );
use base qw( Net::SSH2 );
my %keys;
sub new {
my ( $class, %args ) = @_;
my $self = $class->SUPER::new ( %args );
$keys{ refaddr ( $self ) } = 'value';
bless $self, $class;
return $self;
}
Run Code Online (Sandbox Code Playgroud)