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

前端 未结 12 1995
醉话见心
醉话见心 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条回答
  •  萌比男神i
    2020-11-27 13:24

    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.

提交回复
热议问题