According to the discussion of this thread, I think we can agree that you should not check $! when readline returns a defined value.

The good news is that it seems you can trust $! when readline returns undef. Thus, you can most likely follow the example of perlfunc:

$! = 0; $line = <$file>; if (!defined($line) && $!) { die "error readline: $!"; } elsif (!defined($line)) { print "reached eof\n"; } else { $line=~/(.*)/; print qq(read a line: "$1"); }

I say this because it seems that perl cleares errno when it reads eof, at least starting from version 5.8.1. Try this:

echo $'three\nshort\nlines' > a; perl -we 'open $f, "<", "a"; for(0..3) { $!=10000; $l = <$f>; $s = $! +; warn +(defined($l)?$l=~/(.*)/&&qq/"$1"/:"undef"), " $s\n"; }'
You should get something like
"three" Bad file descriptor "short" Unknown error 10000 "lines" Unknown error 10000 undef undef
The error codes after the first three reads can be anything (so you might get a different error), but note that the error is indeed cleared when eof is read.

I've tried the same with perl 5.8.0, and have seen that it does not clear $!. This is because clearing $! is done in the PerlIOUnix_read funciton (perlio.c), and that function has changed between 5.8.0 and 5.8.1 as tye has noted.

I am still not sure whether perl always clears errno on eof or only in some conditions (it seems likely that it happens only with some kind of filehandles), so you shouldn't take granted what I've just said above.


In reply to Re: readline succeeds but sets $! = EBADF by ambrus
in thread readline succeeds but sets $! = EBADF by ambrus

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.