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

Hi Monks,

I can connect to a remote host using

my $SSH2 = Net::SSH2->new(); $ssh2->connect("server.com") or die;

However, if an invalid server name is given, I get error message:

Net::SSH2::connect: failed to connect to blah:22: Invalid argument at test.pl line 10.

and the program dies.

I need to be able to test if the connection can be made, and then if it can't, I will handle it separately with a wxDialog. I saw people saying you should code a connect like this:

if ($ssh2->connect("server.com")) { ... }

But this produces exactly the same error if the remote host doesn't exist! I'm testing it on strawberry perl in Windows 2000.

Any suggestions would help!
James

Replies are listed 'Best First'.
Re: Net::SSH2 test connection to remote host
by Corion (Patriarch) on Sep 30, 2008 at 10:47 UTC

    See eval:

    my $ssh2 = Net::SSH2->new(); my $res = eval { $ssh2->connect($server)); 1 }; if (my $err = $@) { warn "There was an error connecting to $server: $err"; };
      Thanks for the quick response Corion,

      that worked perfectly!

      Corion what's with the 1 as the last statement in the eval? I don't think I've come across that idiom.

      -derby

        The ; 1 is to make sure I get a true value no matter what the function returns. If it fails, I think there are cases where the block still might return a true value, but I don't know.