rpg
rpg

Reputation: 1652

Perl - Unable to create class variable for child class

I am creating a child class having base class as Net::SSH2. when I am trying to add a class variable I am getting error saying -

Not a HASH reference at F:\temp\fooA.pl line 17.

If I do the same thing wihtout Net::SSH2 then it works fine.

Here is the code :

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;
}

Upvotes: 4

Views: 193

Answers (1)

Egga Hartung
Egga Hartung

Reputation: 1091

It's simple: Net::SSH2 doesnt return a hash ref, but a blessed scalar:

use Scalar::Util qw(reftype);
print reftype($self) . "\n";  # SCALAR

BTW: It's always dangerous to rely on implementation details of third party code.

A possible solution would be to use inside out objects:

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;
}

Upvotes: 5

Related Questions