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
I think this is what you are looking for
File::Slurp
Also have a look at Perl6::Slurp which implements the Perl6 version of slurp and is recommended in the "Perl Best Practices" book.
Some examples....
my @lines = slurp 'filename';
my @lines_chomped = slurp 'filename', { chomp => 1 };
my @lines_utf8 = slurp 'filename', { utf8 => 1 };
You've gotten the general techniques, but I want to put in that Perl sort of discourages you from doing that because it's very often the case that you can do the same thing you're doing one-line-at-a-time, which is inherently far more efficient.
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.
I would recommend an object oriented approach that does not requires modules outside the CORE distribution and will work anywhere:
use strict;
use warnings;
use IO::File;
my $fh = IO::File->new("< $file");
foreach ($fh->getlines) {
do_something($_);
}
$fh->close
that is the famous "slurp mode":
my @lines = <FILEHANDLE> ;
you may also see Perl Slurp Ease