如何在Perl中将文件的行读入数组?
问题描述:
我有一个名为 test.txt 的文件,就像这样:
I have a file named test.txt that is like this:
测试
Foo
Bar
但是我想把每一行放在一个数组中,这样的行:
But I want to put each line in a array and print the lines like this:
line1 line2 line3
line1 line2 line3
But how can I do this?
答
#!/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;