简体   繁体   English

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

[英]How can I read the lines of a file into an array in Perl?

I have a file named test.txt that is like this: 我有一个名为test.txt的文件,如下所示:

Test 测试
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;

Here is my single liner: 这是我的单线:

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

Explanation: 说明:

  • read file by lines into @a array 将文件按行读入@a数组
  • chomp(..) - remove EOL symbols for each line chomp(..) - 删除每行的EOL符号
  • concatenate @a using space as separator 使用空格作为分隔符连接@a
  • print result 打印结果
  • pass file name as parameter 将文件名作为参数传递

The most basic example looks like this: 最基本的示例如下所示:

#!/usr/bin/env perl

use strict;
use warnings;

open(F, "<", "test.txt") or die("Cannot open test.txt: $!\n"); # (1)
my @lines = ();
while(<F>) { chomp; push(@lines, $_); } # (2)
close(F);

print "@lines"; # (3) stringify

(1) is the place where the file is opened. (1)是文件打开的地方。

(2) File handles work nicely within list enviroments (scalar/list environments are defined by the left value), so if you assign an array to a file handle, all the lines are slurped into the array. (2)文件句柄在列表环境中很好地工作(标量/列表环境由左值定义),因此如果将数组分配给文件句柄,则所有行都会插入到数组中。 The lines are delimited (ended) by the value of $/ , the input record separator. 这些行由$/ (输入记录分隔符)的值分隔(结束)。 If you use English; 如果你use English; , you can use $IRS or $INPUT_RECORD_SEPARATOR . ,您可以使用$IRS$INPUT_RECORD_SEPARATOR This value defaults to the newline character \\n ; 此值默认为换行符\\n ;

While this seemed to be a nice idea, I've just forgot the fact that if you print all the lines, the ending \\n will be printed too. 虽然这似乎是一个不错的主意,但我忘了这样一个事实:如果你打印所有的行,结尾\\n也将被打印出来。 Baaad me. 拜我

Originally the code was: 最初的代码是:

my @lines = <F>;

instead of the while loop. 而不是while循环。 This is still a viable alternative, but you should swap (3) with chomp ing and then printing/stringifying all the elements: 这仍然是一个可行的选择,但你应该交换(3) chomp然后打印/字符串化所有元素:

for (@lines) { chomp; }
print "@lines";

(3) Stringifying means converting an array to a string and inserting the value $" between the array elements. This defaults to a space. (3)字符串化意味着将数组转换为字符串并在数组元素之间插入值$" 。默认为空格。

See: the perlvar page . 请参阅: perlvar页面

So the actual 2nd try is: 所以实际的第二次尝试是:

#!/usr/bin/env perl

use strict;
use warnings;

open(F, "<", "test.txt") or die("Cannot open test.txt: $!\n"); # (1)
my @lines = <F>; # (2)
close(F);
chomp(@lines);

print "@lines"; # (3) stringify

One more answer for you to choose from: 还有一个答案供您选择:

#!/usr/bin/env perl

open(FILE, "<", "test.txt") or die("Can't open file");
@lines = <FILE>;
close(FILE);
chomp(@lines);
print join(" ", @lines);

If you find yourself slurping files frequently, you could use the File::Slurp module from CPAN: 如果您经常发现自己正在使用文件,可以使用CPAN中的File :: Slurp模块:

use strict;
use warnings;
use File::Slurp;

my @lines = read_file('test.txt');
chomp @lines;
print "@lines\n";

This is the simplest version I could come up with: 这是我能想到的最简单的版本:

perl -l040 -pe';' < test.txt

Which is roughly equivalent to: 这大致相当于:

perl -pe'
  chomp; $\ = $/; # -l
  $\ = 040;       # -040
'

and: 和:

perl -e'
  LINE:
    while (<>) {
      chomp; $\ = $/; # -l
      $\ = " ";       # -040
    } continue {
      print or die "-p destination: $!\n";
    }
'

This is the code that do this (assume the below code inside script.pl) : 这是执行此操作的代码(假设下面的代码在script.pl中):

use strict;
use warnings
my @array = <> ;
chomp @array;
print "@array";

It is run by: 它由以下人员运行:

scirpt.pl [your file]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM