develooper Front page | perl.perl5.porters | Postings from May 2015

Detecting a read error when using readline

Thread Next
From:
John Wiersba
Date:
May 23, 2015 05:29
Subject:
Detecting a read error when using readline
Message ID:
CAMs4ZVtg=qbJNccQ1tXFRh2QH=OPsjVM+ROGJnhQVHugzOO+OQ@mail.gmail.com
In older doc for readline (but not in the newest doc), it mentions the idiom:

  for (;;) {
    undef $!;
    unless (defined( $line = <> )) {
       last if eof;
       die $! if $!;
     }
  }

to distinguish between EOF and a read error.  That appears to work
properly in perl 5.20.2, but it fails in perl 5.10.1 when $/ == \100,
for example (I almost wrote a bug report for this, but since it's
working in 5.20.2, I declined).  It appears to always work in every
version I've tested it in, if $/ == "\n".
My goal is use readline and still be able to *reliably* distinguish
EOF from a read error.  See also
http://www.perlmonks.org/?node_id=583432 which indicates that this
idiom was failing on Windows under some circumstances.

My questions:

- Is it possible to use readline and reliably distinguish EOF from a
read error, using an idiom which also works on older versions of perl?
- Or do I have to resort to sysread?
- Why was this idiom removed from perldoc?

My test code:

use strict;
use warnings;
$/ = \ shift if @ARGV && $ARGV[0] =~ /^\d+\z/;
my $cnt = 0;
while (1) {
   undef $!;
   if (!defined($_ = <>)) {
      die $! if $!;
      last; # reached EOF
   }
   print $cnt += length, "\n";
}
print "EOF: $cnt\n";

Thanks!
-- John

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About