in reply to Net::SSH2 test connection to remote host

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

Replies are listed 'Best First'.
Re^2: Net::SSH2 test connection to remote host
by derby (Abbot) on Sep 30, 2008 at 11:49 UTC

    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.

        But as it, it's an example of cargo-cult. Sure, $res is true if and only if the eval doesn't fail, but you're not using its result. Instead, you rely on $@ to determine failure. But the entire '; 1' idiom is there because relying on $@ to determine failure can trigger both false positives and false negatives. The correct idiom is:
        my $res = eval {...statements...; 1}; unless ($res) { ... eval failed ... }
Re^2: Net::SSH2 test connection to remote host
by james_ (Novice) on Sep 30, 2008 at 10:59 UTC
    Thanks for the quick response Corion,

    that worked perfectly!