At 19:01 -0800 19/11/02, gene wrote:
An alternative is to read the entire file in (undef $/) and then split it:
My suggestion is to put some code like this in your script:
It's a good solution. Probably for files less than a few hundred k it makes no difference (since you'll need to read the entire file anyway, until the memory usage of storing the whole thing becomes an issue it wont affect anything).

For portability, you should use \012 and \015 explicitly, except for the final default value which should be \n. Here is the code, with the fail counter added to avoid it reading forever in a file with no line endings (not that it is likely to help anyway since you'll presumably follow this up with reading a line...)

# Usage: local $/ = get_line_ending($fh);
# By gene

sub get_line_ending {
my ($fh) = @_;

my $failcount = 33000;
my $char;
while (read $fh, $char, 1 and $failcount-- > 0) {
if ($char eq "\012") {
seek $fh, 0, 0;
return "\012";
} elsif ($char eq "\015") {
if (read $fh, $char, 1 and $char eq "\012") {
seek $fh, 0, 0;
return "\015\012";
} else {
seek $fh, 0, 0;
return "\015";
}
}
}
## what, no line ending?
## return a reasonable default
seek $fh, 0, 0;
return "\n";
}

Suggestions for the above code:
Move the sub into a module.
I have ;-). whether it's worth publishing a CPAN module, I don't know. Perhaps adding it to some existing module?

I assume it's more efficient to read small chunks of bytes rather
than byte by byte.  For most text files this shouldn't matter, but
you may want to alter the reads and also the comparisons if you care.
It would require some timing to figure out if reading a block of characters would be better, possibly something like:

read 256 characters, look for the first \012 or \015 and see what's up (being careful not to accept a \015 as the 256th character as an answer), then try again with a larger read

would be more efficient, but then again, possibly not. It would depend on a lot of things and might vary from OS to OS, so it's probably not worth worrying too much about.

Enjoy,
Peter.


--
<http://www.interarchy.com/> <http://download.interarchy.com/>


Reply via email to