On Thu, Feb 06, 2003 at 12:44:43PM +0100, Louis Pouzin wrote: > I want to read a file by blocks of a certain size. So, "read" is my best friend. But >I have trouble with the eof flag. > It seems that eof is true on the beginning (script 1). > Putting an <IN> command up front seems to clear eof (script 2): > Another way is *not* to use eof (script 3): > > But I'd like to understand how eof really works. > > Thanks > > #!/usr/local/bin/perl -w > # script 1 > $\="\n"; > my ($k,$p,$q) = (0,0,0); my $n = 100000; > open IN, '<truc' or die 'truc not open'; > print 'file info: ', -s 'truc',' chars'; # 3509313 > print 'eof: ',eof;
perldoc -f eof: An eof without an argument uses the last file read as argument. You have not read from any files at this point in your script, so calling eof without an argument is not useful. Perhaps you meant to call eof(IN) instead. However, note the following: Practical hint: you almost never need to use eof in Perl, because the input operators return false values when they run out of data, or if there was an error. And perldoc -f read: Returns the number of bytes actually read, 0 at end of file, or undef if there was an error. So, you could write your loop like this instead: while ($p = read IN, $_, $n) { $k++; } or perhaps: while ($p = read(IN, $_, $n) and $p == $n) { $k++; } But, instead of read(), you can actually read blocks with <>, by setting $/ to a reference to an integer: $/ = \100000; while (<IN>) { $k++; } HTH, Ronald