What's the best way to open and read a file in Perl?

主宰稳场 提交于 2019-11-26 19:43:45
JSBձոգչ

There are no universal standards, but there are reasons to prefer one or another. My preferred form is this:

open( my $input_fh, "<", $input_file ) || die "Can't open $input_file: $!";

The reasons are:

  • You report errors immediately. (Replace "die" with "warn" if that's what you want.)
  • Your filehandle is now reference-counted, so once you're not using it it will be automatically closed. If you use the global name INPUT_FILEHANDLE, then you have to close the file manually or it will stay open until the program exits.
  • The read-mode indicator "<" is separated from the $input_file, increasing readability.

The following is great if the file is small and you know you want all lines:

my @lines = <$input_fh>;

You can even do this, if you need to process all lines as a single string:

my $text = join('', <$input_fh>);

For long files you will want to iterate over lines with while, or use read.

Kent Fredric

If you want the entire file as a single string, there's no need to iterate through it.

use strict;
use warnings;
use Carp;
use English qw( -no_match_vars );
my $data = q{};
{
   local $RS = undef; # This makes it just read the whole thing,
   my $fh;
   croak "Can't open $input_file: $!\n" if not open $fh, '<', $input_file;
   $data = <$fh>;
   croak 'Some Error During Close :/ ' if not close $fh;
}

The above satisfies perlcritic --brutal, which is a good way to test for 'best practices' :). $input_file is still undefined here, but the rest is kosher.

pjf

Having to write 'or die' everywhere drives me nuts. My preferred way to open a file looks like this:

use autodie;

open(my $image_fh, '<', $filename);

While that's very little typing, there are a lot of important things to note which are going on:

  • We're using the autodie pragma, which means that all of Perl's built-ins will throw an exception if something goes wrong. It eliminates the need for writing or die ... in your code, it produces friendly, human-readable error messages, and has lexical scope. It's available from the CPAN.

  • We're using the three-argument version of open. It means that even if we have a funny filename containing characters such as <, > or |, Perl will still do the right thing. In my Perl Security tutorial at OSCON I showed a number of ways to get 2-argument open to misbehave. The notes for this tutorial are available for free download from Perl Training Australia.

  • We're using a scalar file handle. This means that we're not going to be coincidently closing someone else's file handle of the same name, which can happen if we use package file handles. It also means strict can spot typos, and that our file handle will be cleaned up automatically if it goes out of scope.

  • We're using a meaningful file handle. In this case it looks like we're going to write to an image.

  • The file handle ends with _fh. If we see us using it like a regular scalar, then we know that it's probably a mistake.

If your files are small enough that reading the whole thing into memory is feasible, use File::Slurp. It reads and writes full files with a very simple API, plus it does all the error checking so you don't have to.

There is no best way to open and read a file. It's the wrong question to ask. What's in the file? How much data do you need at any point? Do you need all of the data at once? What do you need to do with the data? You need to figure those out before you think about how you need to open and read the file.

Is anything that you are doing now causing you problems? If not, don't you have better problems to solve? :)

Most of your question is merely syntax, and that's all answered in the Perl documentation (especially (perlopentut). You might also like to pick up Learning Perl, which answers most of the problems you have in your question.

Good luck, :)

It's true that there are as many best ways to open a file in Perl as there are

$files_in_the_known_universe * $perl_programmers

...but it's still interesting to see who usually does it which way. My preferred form of slurping (reading the whole file at once) is:

use strict;
use warnings;

use IO::File;

my $file = shift @ARGV or die "what file?";

my $fh = IO::File->new( $file, '<' ) or die "$file: $!";
my $data = do { local $/; <$fh> };
$fh->close();

# If you didn't just run out of memory, you have:
printf "%d characters (possibly bytes)\n", length($data);

And when going line-by-line:

my $fh = IO::File->new( $file, '<' ) or die "$file: $!";
while ( my $line = <$fh> ) {
    print "Better than cat: $line";
}
$fh->close();

Caveat lector of course: these are just the approaches I've committed to muscle memory for everyday work, and they may be radically unsuited to the problem you're trying to solve.

For OO, I like:

use FileHandle;
...
my $handle = FileHandle->new( "< $file_to_read" );
croak( "Could not open '$file_to_read'" ) unless $handle;
...
my $line1 = <$handle>;
my $line2 = $handle->getline;
my @lines = $handle->getlines;
$handle->close;

I once used the

open (FILEIN, "<", $inputfile) or die "...";
my @FileContents = <FILEIN>;
close FILEIN;

boilerplate regularly. Nowadays, I use File::Slurp for small files that I want to hold completely in memory, and Tie::File for big files that I want to scalably address and/or files that I want to change in place.

Read the entire file $file into variable $text with a single line

$text = do {local(@ARGV, $/) = $file ; <>};

or as a function

$text = load_file($file);
sub load_file {local(@ARGV, $/) = @_; <>}

If these programs are just for your productivity, whatever works! Build in as much error handling as you think you need.

Reading in a whole file if it's large may not be the best way long-term to do things, so you may want to process lines as they come in rather than load them up in an array.

One tip I got from one of the chapters in The Pragmatic Programmer (Hunt & Thomas) is that you might want to have the script save a backup of the file for you before it goes to work slicing and dicing.

Ape-inago

The || operator has higher precedence, so it is evaluated first before sending the result to "open"... In the code you've mentioned, use the "or" operator instead, and you wouldn't have that problem.

open INPUT_FILE, "<$input_file"
  or die "Can't open $input_file: $!\n";

Damian Conway does it this way:

$data = readline!open(!((*{!$_},$/)=\$_)) for "filename";

But I don't recommend that to you.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!