Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to open a text file and read it into an array with Perl

Tags:

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;
}

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.

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");
like image 969
Brian Avatar asked Apr 17 '09 17:04

Brian


1 Answers

You have several options, the classic do method:

my @array = do {
    open my $fh, "<", $filename
        or die "could not open $filename: $!";
    <$fh>;
};

The IO::All method:

use IO::All;

my @array = io($filename)->slurp;

The File::Slurp method:

use File::Slurp;

my @array = read_file($filename);

And probably many more, after all TIMTOWTDI.

like image 181
Chas. Owens Avatar answered Sep 20 '22 18:09

Chas. Owens