lightbringer has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I'm trying to create an object instant variable inside the constructor of another class, but the instant variable is not recognized after initialized. Could anyone help me on this one, please.

use Net::Telnet(); package L_Switch; sub new { my $class = shift; my $location = shift; my $ip = shift; my $self = {}; $self -> {'ip'} = $ip; $self -> {'location'} = $location; $self -> {'full_info'} = "asd"; $self -> {'fault'} = ""; $self -> {'time_out'} = ""; $self -> {'telnetConn'} => new Net::Telnet( Timeout => 10, errmode => # if connection is unsucces +sful ( sub { $self -> {'full_info'} = CLIENT . ",," . $ip . ",T +IMEOUT"; $self -> {'fault'} = "-No Response"; $self -> {'time_out'} = 1; } ) ); bless $self, $class; return $self; } sub login { my $self = shift; $self -> {'telnetConn'} -> open($self -> {ip}); $self -> {'telnetConn'} -> login(USERNAME, PASSWORD); } 1;

telnetConn is the instant variable that has problems. I tried to use it in Login method, but the error returned is

Can't call method "open" on an undefined value at L_Switch.pm.

Replies are listed 'Best First'.
Re: Problem initializing an object as an instant variable
by McA (Priest) on Jun 27, 2012 at 02:31 UTC
    Hi,
    IMHO it's a simple typo. Look at:
    $self -> {'telnetConn'} => new Net::Telnet( Timeout => 10, errmode => # if connection is unsuccessful ( sub { $self -> {'full_info'} = CLIENT . ",," . $ip . ",TIMEO +UT"; $self -> {'fault'} = "-No Response"; $self -> {'time_out'} = 1; } ) );

    You don't have an assignment. You used '=>'.

    Please get used to the more correct object instantitation idiom Net::Telnet->new. There are articles out there explaining the subtle differences and pitfalls.

    Best regards
    McA
Re: Problem initializing an object as an instant variable
by muba (Priest) on Jun 27, 2012 at 02:21 UTC

    Do you get any other error messages? What do they tell you?

    Do you use strict; and use warnings;? Are their complaints in any way helpful?

    What is CLIENT in $self -> {'full_info'} = CLIENT . ",," . $ip . ",TIMEOUT";?

    Does the Net::Telnet constructor take errmode as an argument? The documentation says Errmode (mind the capital initial). How flexible is the module about that sort of things? Were there no error messages complaining about this?

    Have you tried to rewrite it as $self -> {'telnetConn'} => Net::Telnet->new(...);?