Easiest way to open a text file and read it into an array with Perl

前端 未结 8 1622
星月不相逢
星月不相逢 2020-12-14 02:46

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          


        
相关标签:
8条回答
  • 2020-12-14 02:55

    I think this is what you are looking for

    File::Slurp

    0 讨论(0)
  • 2020-12-14 02:56

    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 };
    
    0 讨论(0)
  • 2020-12-14 02:59

    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.

    0 讨论(0)
  • 2020-12-14 03:01

    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.

    0 讨论(0)
  • 2020-12-14 03:09

    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
    
    0 讨论(0)
  • 2020-12-14 03:11

    that is the famous "slurp mode":

      my @lines = <FILEHANDLE> ;
    

    you may also see Perl Slurp Ease

    0 讨论(0)
提交回复
热议问题