How to read line by line only CR file with Perl?

I am trying to read a file that has only CR as a line separator. I am using Mac OS X and Perl v.5.8.8. This script should be run on each platform for each type of line separator (CR, LF, CRLF).

My current code is as follows:

open(FILE, "test.txt");

while($record = <FILE>){
    print $record;
}

close(TEST);

Currently, only the last line (or worst) is printed. What's happening? Obviously, I would not want to convert the file. Is it possible?

+3
source share
2 answers

You can set the delimiter using a special variable $/:

local $/ = "\r" # CR, use "\r\n" for CRLF or "\n" for LF
my $line = <FILE>;

. perldoc perlvar.

, , , :

local $/ = undef;
my $content = <FILE>;
my @lines = split /\r\n|\n|\r/, $content;

, , . , $/ undefined , , .

+19

, :

(CR/CRLF/LF), .

, . 'detectEndOfLine' '\ r', '\n', , ( '\ r' '\n' char -by- char ).

my $file = "test.txt";
local $/ = detectEndOfLine($file);
open(IN, $file) or die "Can't open file \"$file\" for reading: $!\n";
while(<IN>) {
    s/\r\n|\n|\r$//;
    print "$_\n";
}

sub detectEndOfLine {
    my $file = $_[0];
    my $size = -s $file;
    print "\"$size\"\n";

    open(IN, $file) or die "Can't open file \"$file\" for reading: $!\n";
    for(my $i = $size; $i >= 0; --$i) {
        seek(IN, $i, 0);
        $_ = <IN>;
        my $sym = substr($_, 0, 1);
        return $sym if( $sym eq "\n" or $sym eq "\r" );
    }
    return undef;
}
+1

Source: https://habr.com/ru/post/1749471/


All Articles