使用 Perl 打开文本文件并将其读入数组的最简单方法 [英] Easiest way to open a text file and read it into an array with Perl
问题描述
为我拥有的每个脚本添加一个标准的 Perl 文件打开函数有点烦人:
Adding a standard Perl file open function to each script I have is a bit annoying:
sub openfile{
(my $filename) = @_;
open FILE,"$filename" or die $!;
my @lines = <FILE>;
return @lines;
}
我可以创建一个 Perl 模块来执行此操作,但这太简单了,我相信应该已经有一个了.
and I can create a Perl module to do this, but this is so simple I'm sure there should be one out there already.
我正在尝试找到一种将文本文件读入数组的方法,但我似乎找不到可以完成这项简单任务的 Perl 模块...随附标准 5.10 安装.
I'm trying to find a way to read a text file into an array, and I cant seem to find a Perl module out there that can do this simple task... maybe I'm looking too hard and it already came with the standard 5.10 install.
最好我相信它看起来像这样:
Optimally I believe it would look something like this:
my @lines = Module::File::Read("c:somefolderstructurefile.txt");
推荐答案
你有几个选择,经典的do方法:
You have several options, the classic do method:
my @array = do {
open my $fh, "<", $filename
or die "could not open $filename: $!";
<$fh>;
};
IO::All 方法:
use IO::All;
my @array = io($filename)->slurp;
File::Slurp 方法:
use File::Slurp;
my @array = read_file($filename);
也许还有更多,毕竟TIMTOWTDI.
这篇关于使用 Perl 打开文本文件并将其读入数组的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!