\$\begingroup\$
\$\endgroup\$
0
I would like to detect which is the line-endings type of a file. I wrote this function:
open my $fh, '<afile.txt';
seteol($fh);
Here the eol detection subroutine:
sub seteol {
my $fh = shift;
my $byte;
my $i = 0;
while (sysread($fh, $byte, 1)) {
if($byte eq "\n") {
$/ = "\n";
return 0;
}
elsif($byte eq "\r") {
sysread($fh, $byte, 1);
if($byte eq "\n") {
$/ = "\r\n";
return 0;
} else {
$/ = "\r";
return 0;
}
}
last if $i++ > 65535;
}
return -1;
seek($fh,0,0);
}
I am wondering if I can do a better job with only core-modules.
1 Answer 1
\$\begingroup\$
\$\endgroup\$
3
It reads file by 4096 chars in hope to find EOL,
local $/ = seteol($fh) // $/;
sub seteol {
my $fh = shift;
local $/ = 4096円;
my $line = "";
while (my $b = <$fh>) {
$line .= $b;
last if $line =~ /(\R)/;
}
seek($fh,0,0);
return 1ドル if 1ドル;
warn "Unknown EOL";
return;
}
answered Sep 25, 2014 at 8:56
-
\$\begingroup\$ @coin check update \$\endgroup\$mpapec– mpapec2014年09月25日 09:22:53 +00:00Commented Sep 25, 2014 at 9:22
-
\$\begingroup\$ Why did you chose 4096? \$\endgroup\$nowox– nowox2014年09月25日 12:55:20 +00:00Commented Sep 25, 2014 at 12:55
-
\$\begingroup\$ @coin for no particular reason, it is 4kb in a hope that it would be enough to find EOL with first read. \$\endgroup\$mpapec– mpapec2014年09月25日 17:33:01 +00:00Commented Sep 25, 2014 at 17:33
lang-perl