如何读取.txt文件并将其存储到数组中

时间:2019-02-23 16:24:53

标签: arrays perl read-text

我知道这是一个非常简单的问题,但是我无法弄清楚如何以所需的方式将所有值存储在数组中。 这是.txt文件的一小部分:

0 A R N D
A 2 -2 0 0
R -2 6 0 -1
N 0 0 2 2
D 0 -1 2 4

每个值都由两个空格分隔-如果下一个值是正数-或一个空格和'-'-如果下一个值是负数

代码如下:

use strict;
use warnings;

open my $infile, '<', 'PAM250.txt' or die $!;
my $line;
my @array;

while($line = <$infile>) 
{
    $line =~ /^$/ and die "Blank line detected at $.\n";
    $line =~ /^#/ and next; #skips the commented lines at the beginning
    @array = $line;
    print "@array"; #Prints the array after each line is read
};

print "\n\n@array"; #only prints the last line of the array ?

我了解@array仅保留传递给它的最后一行。有没有一种方法可以让@array保存所有行?

4 个答案:

答案 0 :(得分:1)

您正在寻找push

push @array, $line;

毫无疑问,您首先要在chomp之前添加所有换行符。

答案 1 :(得分:1)

如果文件比计算机的可用内存小,那么您可以简单地使用以下方法将文件内容读入数组中

$_POST['item_meta'][30]

如果您要读取一个非常大的文件,则最好像这样做一样逐行读取,但使用PUSH在数组末尾添加每一行。

open my $infile, '<', 'PAM250.txt' or die $!;
my @array = <$infile>;
close $infile;

我建议您还阅读更多有关数组manipulating functions in perl

的信息。

答案 2 :(得分:0)

您不清楚要达到的目标。

每一行都是数组的元素吗?

每一行都是数组中的一个数组,您的“单词”是该数组的元素吗?

随便。

这是您同时可以实现的两种方式:

use strict;
use warnings;
use Data::Dumper;

# Read all lines into your array, after removing the \n
my @array= map { chomp; $_ } <>;

# show it
print Dumper \@array;

# Make each line an array so that you have an array of arrays
$_= [ split ] foreach @array;

# show it
print Dumper \@array;

答案 3 :(得分:-1)

try this...


sub room
{
   my $result = "";
   open(FILE, <$_[0]);
   while (<FILE>) { $return .= $_; }
   close(FILE);
   return $result;
}

so you have a basic functionality without great words. the suggest before contains the risk to fail on large files. fastest safe way is that. call it as you like...

my @array = &room('/etc/passwd');

print room('/etc/passwd');

you can shorten, rename as your convinience believes.

to the kidding ducks nearby: by this way the the push was replaced by simplictiy. a text-file contains linebreaks. the traditional push removes the linebreak and pushing up just the line. the construction of an array is a simple string with linebreaks. now contain the steplength...