将数据文件读入数组的正确方法

时间:2012-01-22 18:18:50

标签: perl

我有一个数据文件,每行有一个数字,比如

10
20
30
40

如何读取此文件并将数据存储到数组中?

这样我就可以对这个数组进行一些操作。

6 个答案:

答案 0 :(得分:73)

只需将文件读入数组,每个元素一行,这是微不足道的:

open my $handle, '<', $path_to_file;
chomp(my @lines = <$handle>);
close $handle;

现在文件的行位于数组@lines

如果您想确保openclose有错误处理,请执行以下操作(在下面的剪辑中,我们open the file in UTF-8 mode):

my $handle;
unless (open $handle, "<:encoding(utf8)", $path_to_file) {
   print STDERR "Could not open file '$path_to_file': $!\n";
   # we return 'undefined', we could also 'die' or 'croak'
   return undef
}
chomp(my @lines = <$handle>);
unless (close $handle) {
   # what does it mean if close yields an error and you are just reading?
   print STDERR "Don't care error while closing '$path_to_file': $!\n";
} 

答案 1 :(得分:11)

最简单的方法是使用File::Slurp模块:

use File::Slurp;
my @lines = read_file("filename", chomp => 1); # will chomp() each line

如果您需要对每一行进行一些验证,可以在grep前面使用read_file

例如,过滤行只包含整数:

my @lines = grep { /^\d+$/ } read_file("filename", chomp => 1);

答案 2 :(得分:10)

我喜欢......

@data = `cat /var/tmp/somefile`;

它并不像其他人那样迷人,但是,它的工作方式完全相同。和...

$todays_data = '/var/tmp/somefile' ;
open INFILE, "$todays_data" ; 
@data = <INFILE> ; 
close INFILE ;

干杯。

答案 3 :(得分:1)

Tie::File就是您所需要的:

  

<强>概要

# This file documents Tie::File version 0.98
use Tie::File;

tie @array, 'Tie::File', 'filename' or die ...;

$array[13] = 'blah';     # line 13 of the file is now 'blah'
print $array[42];        # display line 42 of the file

$n_recs = @array;        # how many records are in the file?
$#array -= 2;            # chop two records off the end


for (@array) {
  s/PERL/Perl/g;         # Replace PERL with Perl everywhere in the file
}

# These are just like regular push, pop, unshift, shift, and splice
# Except that they modify the file in the way you would expect

push @array, new recs...;
my $r1 = pop @array;
unshift @array, new recs...;
my $r2 = shift @array;
@old_recs = splice @array, 3, 7, new recs...;

untie @array;            # all finished

答案 4 :(得分:1)

open AAAA,"/filepath/filename.txt";
my @array = <AAAA>; # read the file into an array of lines
close AAAA;

答案 5 :(得分:0)

这取决于文件的大小!上面的解决方案倾向于使用便捷的速记方式将整个文件复制到内存中,这在很多情况下都可以使用。

对于非常大的文件,您可能需要使用流式设计,其中按行或成块读取文件,处理块,然后将其从内存中丢弃。

如果需要的话,请参见reading line by line with perl上的答案。