如何在Perl中将文件行读入数组?

Nat*_*pos 10 perl file-io

我有一个名为test.txt的文件,如下所示:

测试
Foo
Bar

但是我想把每一行放在一个数组中并打印出这样的行:

line1 line2 line3

但是我怎么能这样做呢?

Cor*_*rey 21

#!/usr/bin/env perl
use strict;
use warnings;

my @array;
open(my $fh, "<", "test.txt")
    or die "Failed to open file: $!\n";
while(<$fh>) { 
    chomp; 
    push @array, $_;
} 
close $fh;

print join " ", @array;
Run Code Online (Sandbox Code Playgroud)

  • 您应该检查文件是否已成功打开.总是.或者`使用autodie;` (7认同)

Iva*_*uev 14

这是我的单线:

perl -e 'chomp(@a = <>); print join(" ", @a)' test.txt
Run Code Online (Sandbox Code Playgroud)

说明:

  • 将文件按行读入@a数组
  • chomp(..) - 删除每行的EOL符号
  • @a使用空格作为分隔符连接
  • 打印结果
  • 将文件名作为参数传递

  • `perl -le'chomp(@a = <>); 打印"@a"'文件..` (3认同)