in reply to Re: Count number of lines in a text file
in thread Count number of lines in a text file
correction to the "fixed" routines in the demonstration code - it did not handle the "good" EOL case correctly because the "tr" removed the EOL and the original code thought the (good) EOL was missing as a result (I guess I learn something every day). this fix may not be perfect - I think it will return 1 for an empty file (untested) but I am sure there is a fix for that if someone really wants to do it.
I will not be offended if someone finds yet another problem (besides the empty file problem) and comes up with a solution. that is what this site is for - to help people do a better job writing Perl code and to teach people little things about Perl that they may not have known or thought much about.
sub test_fixed_block_read($) { my $block_size=$_[0]; open TIN,"<$test_file"; binmode TIN; my ($data, $n); my $newlinecount=0; my $block_ends_with_eol=0; while ((read TIN, $data, $_[0]) != 0) { $block_ends_with_eol=1 if (substr $data,-1,1) eq "\n"; $newlinecount+=($data =~ tr/\012//); } close(TIN); $newlinecount++ if (!$block_ends_with_eol); print ">>>test_fixed_block_read: $newlinecount\n"; } sub test_fixed_block_sysread($) { my $block_size=$_[0]; open TIN,"<$test_file"; my ($data, $n); my $newlinecount=0; my $block_ends_with_eol=0; while ((sysread TIN, $data, $_[0]) != 0) { $block_ends_with_eol=1 if (substr $data,-1,1) eq "\n"; $newlinecount+=($data =~ tr/\012//); } close(TIN); $newlinecount++ if (!$block_ends_with_eol); print ">>>test_fixed_block_sysread: $newlinecount\n"; }
|
|---|