【问题标题】:Perl - Reading file linesPerl - 读取文件行
【发布时间】:2013-07-11 20:22:24
【问题描述】:

我正在尝试使用以下代码读取文件中的行。但是这段代码的结果是打印与文档行相同的行。

open (file_to_rand, "./files/file07.txt") or die "Could not open file";
foreach $line (<file_to_rand>) {
    push(@array,$line);
}
close(file_to_rand);

这段代码有什么问题?

【问题讨论】:

  • 那么问题是什么?
  • 不,这段代码的“结果”是不打印任何东西。这段代码中唯一可能输出任何东西的是die。另外,"to print the same line as lines the document has"这句话是语法错误,没有任何意义。

标签: perl file foreach line


【解决方案1】:

如果您只想将所有行读入数组(这对大文件无效):

open my $fh, "<",  "./files/file07.txt" or die "Could not open file";
my @lines = readline($fh);
close $fh;
#possible you need to remove new line character at the end of each line:
chomp @lines;

顺便说一句:它是 Perl 而不是 PERL

【讨论】:

  • 除非人们一直在谈论的这个 PERL 是一种完全不同的动物,像我们这样的普通人从未听说过。
猜你喜欢
  • 1970-01-01
  • 2013-11-14
  • 2017-08-05
  • 1970-01-01
  • 1970-01-01
  • 2011-07-20
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
相关资源
最近更新 更多