How to get rid of imperative file opening in Perl?

open( my $handle, '<', 'file.dat' ) or die $!;
my @data = map { do_things($_) } <$handle>;
close $handle;

This imperative open and close above stand out like an eyesore in otherwise nice code. Is there a way to write this in a cleaner way? I could write my own read_file subroutine, but there should be something like this already.

sub read_file {
    open( my $handle, '<', $_[0] ) or croak $!;
    return <$handle>;
}
my @data = map { do_things($_) } read_file('file.dat');

Efficiency is not important, but the solution should be cross-platform.

5
задан Tim 28 May 2011 в 08:59
поделиться