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

前端 未结 12 2033
醉话见心
醉话见心 2020-11-27 13:11

Please note - I am not looking for the \"right\" way to open/read a file, or the way I should open/read a file every single time. I am just interested to find out what way m

12条回答
  •  误落风尘
    2020-11-27 13:15

    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.

提交回复
热议问题