Perl文件读取:在列表上下文中读取时组合多行

时间:2016-08-20 01:18:52

标签: perl

我正在使用以下代码阅读文件:

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

@lines = <$myfile>;

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

close myfile;

该文件的内容是:

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

但该计划的输出是:

Hellhound on My Trailsuesdudgement Day

看起来代码只读取一行,并用读取的新行替换第一个字符。我尝试过不同的文件。只打印一行,基本上汇总在所有行上。

2 个答案:

答案 0 :(得分:2)

原始文件在每行末尾只有一个回车符(CR),如果它应该有一个换行符(LF),或者如果它来自Windows系统并且你在Linux上读它,可能同时包含CR和LF

没有任何新行来分割数据,@lines只有一个元素,其中包含整个文件内容

将该文本打印到终端会导致所有行显示在您看到的彼此之上

您需要修复文件的创建,但同时您可以通过更改Perl的记录分隔符$/来正确阅读

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;

答案 1 :(得分:0)

请检查原始脚本和发布的脚本是否相同。 你确实提到最后一行只是你的示例程序打印。它没有赢。它将打印整行。

始终将use warnings;use strict;放在程序的顶部。

然后将整个文件存储到数组中然后从数组中读取是一种非常糟糕的方法。请改用while循环。

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

 while(<$myfile>)
 {
     print ; # Data are store into the default variable $_. So no need to mention the $_ in print statement.

 }

以下脚本将生成您提到的输出。

foreach (@lines)
{
   $line = $_; # this or
   @new = $_; # this
}
print $line;  #last line
print @new; #last line

如果要将特定数据存储到另一个变量中,请查看字符串($)的连接以及数组的推送或非移位(@)