使用Perl打开文本文件并将其读入数组的最简单方法 [英] Easiest way to open a text file and read it into an array with Perl

查看:636
本文介绍了使用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:\some\folder\structure\file.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆