Dirk80 has asked for the wisdom of the Perl Monks concerning the following question:
Hi,
I want to get rid of the line ending troubles. Until now I had files which had these line endings: 0D 0A (Windows), 0A (Unix), 0D (early MAC). The last file I've seen had mixed MAC and Unix line endings and that was then the reason why my code was not working.
I am now seeking for a solution which is reading a file line per line independent of the three line ending types. Also my goal is it that the line ending is chomped, so that I only have the data of each line stored in an array.
I tried to solve this with the following code:
But the read code is not working and I don't know why. Any hints are welcome. Here I wrote some other code to read the file with the differrent line endings. This code is working.#!/usr/bin/perl use strict; use warnings; use Perl6::Slurp; # generate test file "le.txt" my $win_line = "Windows\r\n"; my $unix_line = "Unix\n"; my $mac_line = "Mac\r"; open(my $fh, ">", "le.txt"); binmode($fh); print $fh $win_line; print $fh $unix_line; print $fh $mac_line; close($fh); # read file with slurp my @lines = slurp("le.txt", {chomp => 1, irs => qr/(\r\n)|(\n)|(\r)/}) +; for my $line (@lines) { print $line . "\n"; }
# read file my $file_content; { local $/ = undef; # no input data record separator --> file conten +t will be stored in one scalar open(my $fh, "<", "le.txt"); binmode($fh); $file_content = <$fh>; close($fh); } (my $space_file_content = $file_content) =~ s/(\r\n)|(\n)|(\r)/ /g; for my $line (split(/ /, $space_file_content)) { print $line . "\n"; }
Although the second solution is working it would be very interesting for me how you would solve this problem and why my slurp code is not working.
Thank you very much for your help.
Dirk
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: line ending troubles
by kennethk (Abbot) on Dec 21, 2009 at 20:31 UTC | |
by Dirk80 (Pilgrim) on Dec 22, 2009 at 22:08 UTC | |
by kennethk (Abbot) on Dec 22, 2009 at 23:01 UTC | |
by Dirk80 (Pilgrim) on Dec 25, 2009 at 00:31 UTC | |
by kennethk (Abbot) on Dec 28, 2009 at 22:18 UTC | |
|
Re: line ending troubles
by almut (Canon) on Dec 21, 2009 at 22:24 UTC | |
by Dirk80 (Pilgrim) on Dec 22, 2009 at 22:23 UTC | |
by almut (Canon) on Dec 22, 2009 at 22:55 UTC | |
by Dirk80 (Pilgrim) on Dec 26, 2009 at 16:22 UTC | |
by almut (Canon) on Dec 27, 2009 at 23:10 UTC | |
|
Re: line ending troubles
by planetscape (Chancellor) on Dec 22, 2009 at 00:22 UTC | |
|
Re: line ending troubles
by bobf (Monsignor) on Dec 21, 2009 at 23:51 UTC |