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

Perl 将数据文件读入数组的正确方法,perl,Perl,我有一个数据文件,每行有一个数字,比如 10 20 30 40 如何读取此文件并将数据存储到数组中 以便我可以在此阵列上执行一些操作。是您需要的: 简介 # 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' p

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

10
20
30
40
如何读取此文件并将数据存储到数组中

以便我可以在此阵列上执行一些操作。

是您需要的:

简介

# 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

仅将文件读入数组(每个元素一行)是很简单的:

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

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

use File::Slurp;
my @lines = read_file("filename", chomp => 1); # will chomp() each line
如果您需要对每一行进行一些验证,您可以在
read\u file
前面使用
grep

例如,仅包含整数的筛选行:

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

@data = `cat /var/tmp/somefile`;
它没有其他的那么迷人,但是,它仍然有效。而且

$todays_data = '/var/tmp/somefile' ;
open INFILE, "$todays_data" ; 
@data = <INFILE> ; 
close INFILE ;
$todays_data='/var/tmp/somefile';
打开内嵌,“$todays\u数据”;
@数据=;
封闭填充;
干杯。

打开AAAA,“/filepath/filename.txt”;
open AAAA,"/filepath/filename.txt";
my @array = <AAAA>; # read the file into an array of lines
close AAAA;
我的@array=;#将文件读入一行数组 关闭AAAA;
这取决于文件的大小!上面的解决方案倾向于使用方便的速记方式将整个文件复制到内存中,这在许多情况下都是可行的

对于非常大的文件,您可能需要使用流式设计,通过行或卡盘读取文件,处理块,然后从内存中丢弃它们


如果这是您需要的,请参阅上的答案

IMHO
Tie::File
对于读取文件并将内容放入数组这样的简单任务来说是一种过分的技巧。除非你的文件很大,否则就太过分了。你忘了吃东西了。也许这会更好:my@data=map{chomp$\u;$\ u}读取文件(“文件名”);起初我没有注意到,文件的每一行都包含一个数字。因此,最好将数字的正则表达式放入
map
而不是
chomp
。更新。首先。如果有人真的需要chomp(),那么使用选项read_file(“filename”,chomp=>1)而不是map。第二我不认为有人真的需要验证。问题不在于如何从文件中读取数字。第三你不会检查像3.1415这样的数字。向前地您可能希望使用grep{/^\d+/}而不是map.1。酷。4.你说得对<代码>grep在这种情况下更为明显。Updated.File::Slurper可能是比File::Slurper更好的解决方案。您应该通过检查返回值或使用autodie来处理“打开”失败的情况。为了正确,您还应该对“close”执行相同的操作。我建议添加
chomp
@data=grep{chomp;}`cat/var/tmp/somefile`这不是一个很好或安全的方法。看,它不是特别安全,但如果你不在乎,它很好。我通常加上'而不是$?或者死在“现场诊断失败”的情况下。请添加一些措辞来解释您的答案。
open AAAA,"/filepath/filename.txt";
my @array = <AAAA>; # read the file into an array of lines
close AAAA;