2
\$\begingroup\$

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.

asked Sep 25, 2014 at 7:51
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

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
\$\endgroup\$
3
  • \$\begingroup\$ @coin check update \$\endgroup\$ Commented Sep 25, 2014 at 9:22
  • \$\begingroup\$ Why did you chose 4096? \$\endgroup\$ Commented 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\$ Commented Sep 25, 2014 at 17:33

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.