Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Pass object to subroutine.

by tacoking92 (Novice)
on Nov 15, 2011 at 18:55 UTC ( #938236=perlquestion: print w/replies, xml ) Need Help??
tacoking92 has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, first post here. Hopefully someone can help me figure out my little problem I'm fighting with.

I'm attempting to pass an Net::OpenSSH object between subroutines and I'm finding it pretty difficult to do.

Here's what I'm trying.
my $ssh = login($user, $pass, $host); test(\$ssh); sub login { ($user, $pass, $host) = @_; my $ssh = Net::OpenSSH -> new($host, user=>$user, password=> $pass); return $ssh; } sub test { $ssh2 = shift; $output = $ssh2 -> capture("ls /tmp"); print $output; }

I get the following error: "Can't call method "capture" on unblessed reference at ./"

Is there a way I can pass the object reference between the subroutines?

Thanks for the help.

Replies are listed 'Best First'.
Re: Pass object to subroutine.
by MidLifeXis (Monsignor) on Nov 15, 2011 at 19:01 UTC
    my $ssh = login($user, $pass, $host); test(\$ssh);

    $ssh is already a blessed reference. If you pass it to test() like test(\$ssh), you are passing an unblessed reference to a blessed reference. You should pass it to test like test($ssh).

    Update: See also


Re: Pass object to subroutine.
by mrstlee (Beadle) on Nov 15, 2011 at 22:09 UTC
    Try this to see the difference between $ssh & \$ssh:
    use Data::Dumper; my $ssh = login($user, $pass, $host); print Dumper $ssh; print Dumper \$ssh;

    Objects in perl are often, but not always, references to a hash that has been "bless"ed into a particular namespace. In this case Net::OpenSSH->new returns a reference to a hash. In fact you can bless any reference - array refs, scalar refs, even sub-routine refs

    It's easy to create your own blessed references

    use Data::Dumper; my $obj_ref = bless {} , 'Any::Old::Perl::Identifier'; sub Any::Old::Perl::Identifier::make_hay{ my ($self) = @_; $self->{'foo'} = 'hay'; } $obj_ref->make_hay(); print ref $obj_ref, "\n"; print ref \$obj_ref, "\n"; print Dumper $obj_ref;
    Any::Old::Perl::Identifier REF $VAR1 = bless( { 'foo' => 'hay' }, 'Any::Old::Perl::Identifier' );
    You can see that the obj_ref has made hay.

    Refs can be a bit confusing. Try the perlreftut tutorial in the core perl documentation.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://938236]
Approved by ww
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (2)
As of 2018-04-20 20:55 GMT
Find Nodes?
    Voting Booth?