【问题标题】:Read newline delimited file in Perl在 Perl 中读取换行符分隔的文件
【发布时间】:2013-08-01 23:53:14
【问题描述】:

我正在尝试将换行符分隔的文件读入 Perl 中的数组。我不希望换行符成为数组的一部分,因为元素是稍后读取的文件名。也就是说,每个元素都应该是“foo”而不是“foo\n”。我过去使用 Stack Overflow 问题 Read a file into an array using PerlNewline Delimited Input 中提倡的方法成功地做到了这一点。

我的代码是:

open(IN, "< test") or die ("Couldn't open");
@arr = <IN>;
print("$arr[0] $arr[1]")

我的文件“测试”是:

a
b
c
d
e

我的预期输出是:

a b

我的实际输出是:

a
 b

我真的不明白我做错了什么。如何将这些文件读入数组?

【问题讨论】:

    标签: perl input delimiter


    【解决方案1】:

    这是我通常从文件中读取的方式。

    open (my $in, "<", "test") or die $!;
    my @arr;
    
    while (my $line = <$in>) {
      chomp $line;
      push @arr, $line;
    }
    
    close ($in);
    

    chomp 将从读取的行中删除换行符。您还应该使用open 的三参数版本。

    【讨论】:

      【解决方案2】:
      • 把文件路径放在自己的变量里,这样可以方便 改变了。
      • 使用 3 参数 open。
      • 测试所有打开、打印和关闭是否成功,如果没有,则打印错误和文件名。

      试试:

      #!/usr/bin/env perl
      
      use strict;
      use warnings;
      
      # --------------------------------------
      
      use charnames qw( :full :short   );
      use English   qw( -no_match_vars );  # Avoids regex performance penalty
      
      # conditional compile DEBUGging statements
      # See http://lookatperl.blogspot.ca/2013/07/a-look-at-conditional-compiling-of.html
      use constant DEBUG => $ENV{DEBUG};
      
      # --------------------------------------
      
      # put file path in a variable so it can be easily changed
      my $file = 'test';
      
      open my $in_fh, '<', $file or die "could not open $file: $OS_ERROR\n";
      chomp( my @arr = <$in_fh> );
      close $in_fh or die "could not close $file: $OS_ERROR\n";
      
      print "@arr[ 0 .. 1 ]\n";
      

      【讨论】:

        【解决方案3】:

        一个不那么冗长的选项是使用File::Slurp::read_file

        my $array_ref = read_file 'test', chomp => 1, array_ref => 1;
        

        当且仅当,您仍然需要保存文件名列表。

        否则,

        my $filename = 'test';
        open (my $fh, "<", $filename) or die "Cannot open '$filename': $!";
        
        while (my $next_file = <$fh>) {
          chomp $next_file;
          do_something($next_file);
        }
        
        close ($fh);
        

        不必保留文件列表,从而节省内存。

        此外,您最好使用$next_file =~ s/\s+\z// 而不是chomp,除非您的用例确实需要在文件名中允许尾随空格。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-16
          • 2013-04-22
          • 2020-11-21
          • 2010-10-07
          • 2019-12-07
          相关资源
          最近更新 更多