简体   繁体   English

Perl-将文本文件逐行读入数组

[英]Perl - read text file line by line into array

I have little experience about perl, trying to read simple text file line by line and put all objects in to array. 我对perl经验很少,试图逐行读取简单的文本文件并将所有对象放入数组。 Could you please help ? 能否请你帮忙 ?

Text File: 文本文件:

AAA
BBB
CCC
DDD
EEE

Needs to have access for each object in array by index to get access for DDD element for example. 需要按索引访问数组中的每个对象,以获取对DDD元素的访问。

THX 谢谢

open(my $fh, '<', $qfn)
   or die("Can't open $qfn: $!\n");

my @a = <$fh>;
chomp @a;

As for the last paragraph, I don't know if you mean 至于最后一段,我不知道你的意思是

$a[3]

or 要么

my @matching_indexes = grep { $_ eq 'DDD' } 0..$#a;

Try this: 尝试这个:

use strict;
use warnings;

my $file = "fileName";
open (my $FH, '<', $file) or die "Can't open '$file' for read: $!";
my @lines;
while (my $line = <$FH>) {
    push (@lines, $line);
}
close $FH or die "Cannot close $file: $!";

print @lines;

To access an array in Perl, use [] and $ . 要在Perl中访问数组,请使用[]$ The index of the first element of an array is 0 . 数组的第一个元素的索引为0 Therefore, 因此,

  $lines[3] # contains DDD

see more here : http://perl101.org/arrays.html 在此处查看更多信息: http : //perl101.org/arrays.html

Your "requirements" here seem extremely minimal and I agree with @ikegami it's hard to tell if you want to match against text in the array or print out an element by index. 您的“要求”在这里似乎非常少 ,我同意@ikegami,很难说是要与数组中的文本进行匹配还是要按索引打印出一个元素。 Perhaps if you read through perlintro you can add to your question and ask for more advanced help based on code you might try writing yourself. 也许如果您通读perlintro可以添加您的问题,并根据您可能会尝试编写的代码寻求更高级的帮助。

Here is a command line that does what your question originally asked. 这是执行您的问题最初要求的命令行。 If you run perldoc perlrun on your system it will show you the various command line switches you can use for perl one-liners. 如果在系统上运行perldoc perlrun ,它将向您显示可用于perl单线的各种命令行开关。

  • -0400 - slurps input -0400 -吸食输入
  • -a - autosplits the file into an array called @F using a single white space as the split character. -a -文件autosplits成称为阵列@F使用单个空格作为分割符。
  • -n - run in an implicit while (<>) { } loop that reads input from the file on -n在隐式while (<>) { }循环中运行,该循环从文件上读取输入
  • -E - execute the script between ' ' -E执行' '之间的脚本

So with lines.txt equal to your text file above: 因此, lines.txt等于上面的文本文件:

   `perl -0400 -a -n -E 'say $F[3];' lines.txt`

outputs: DDD 输出: DDD

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

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