Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl read file error

Tags:

file-io

perl

I have to read a big (BIG) file in memory, line by line, using perl. In case of some error, function open() does return false and $! is set to the system error. But, if I get some errors reading the file? I use this code:

open(STATISTICS, "<" . $statisticsFile) or die "Can't open statistics file $statisticsFile ($!)";
while (<STATISTICS>) {
  my $line = $_;
  ...
}
close($STATISTICS);

Any hint?

like image 674
MarcoS Avatar asked Sep 22 '26 02:09

MarcoS


1 Answers

You can change your code to work as shown below.

You seem to be using both STATISTICS and $STATISTICS for your file handle. Since lexical handles are prefereable I have used $stat here.

open my $stat, "<" . $statisticsFile
    or die "Can't open statistics file $statisticsFile: $!";

until (eof $stat) {
  my $line = <$stat>;
  defined $line or die "Read failure on statistics file $statisticsFile: $!";
  ...
}

close($stat);
like image 82
Borodin Avatar answered Sep 24 '26 17:09

Borodin