Aditya Aditya - 3 months ago 11
Perl Question

Perl File Read: multiple lines combined while reading in list context

I am reading a file using the following code:

open ($myfile, "<file.txt") or die "Could not open the file";

@lines = <$myfile>;

foreach $line (@lines){
print $line;
}

close myfile;


The contents of the file are:

Crossroads Blues
Terraplane Blues
Come on in My Kitchen
Walking Blues
Mister Jelly Roll Maker
Last Fair Deal Gone Down
32-20 Blues
Kindhearted Woman Blues
If I Had Possession Over Judgement Day
Preaching Blues
Blind Willie's Blues
When You Got a Good Friend
Rambling on My Mind
Stones in My Passway
Wild Jelly Roll Blues
Traveling Riverside Blues
Roll My Jellyroll
Milkcow's Calf Blues
Me and the Devil Blues
Hellhound on My Trail


But the output of the program is:

Hellhound on My Trailsuesdudgement Day


It looks like the code reads only one line, and replaces the first characters with the new line that is read. I have tried different files. Only one line is printed, which is basically aggregated over all the lines.

Answer

Your original file has just a carriage-return (CR) at the end of each line when it should have a linefeed (LF) or possibly both CR and LF if it originated from a Windows system and you are reading it on Linux

You need to fix the creation of your file, but in the mean time you can read it correctly by changing Perl's record separator $/ like this

use strict;
use warnings 'all';

open my $fh, '<', 'file.txt' or die "Could not open the file: $!";

my @lines = do {
    local $/ = "\r";
    <$fh>;
};

chomp @lines;

print "$_\n" for @lines;