The problem is that eval { } makes a scope for the statements to be executed. On scope exit, code may be executed (for instance, DESTROY methods). That code can clear $@, or set it - it may even call eval itself.

That's the reason you cannot trust $@ to be set if, and only if, the eval failed.

Here's an example.

#!/usr/bin/perl use 5.010; use strict; use warnings; use Test::More tests => 3; eval {my $x = bless [], 'one'}; is $@, ""; eval {my $x = bless [], 'two'}; is $@, ""; eval {my $x = bless [], 'three'; die "foo\n";}; is $@, "foo\n"; __END__ 1..3 ok 1 ok 2 ok 3
Now we change the code by adding some DESTROY methods - and note that this is the only change in the code.
#!/usr/bin/perl use 5.010; use strict; use warnings; use Test::More tests => 3; eval {my $x = bless [], 'one'}; is $@, ""; eval {my $x = bless [], 'two'}; is $@, ""; eval {my $x = bless [], 'three'; die "foo\n";}; is $@, "foo\n"; sub one::DESTROY {1;} sub two::DESTROY {$@ = "foo";} sub three::DESTROY {$@ = "";} __END__ 1..3 ok 1 not ok 2 # Failed test at /tmp/test line 11. # got: 'foo' # expected: '' not ok 3 # Failed test at /tmp/test line 12. # got: '' # expected: 'foo # ' # Looks like you failed 2 tests of 3.
As you can see, after the second eval $@ is set where you don't expect it to be (the eval succeeded), and while the third eval died, $@ is false.

And note that while I did direct assignment to $@ in the DESTROY methods, I could also have used evals in the DESTROY methods to create false positive or negatives.


In reply to Re^6: Net::SSH2 test connection to remote host by JavaFan
in thread Net::SSH2 test connection to remote host by james_

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.