2013-08-01 23 views
0

分隔的文件我想讀一個換行符分隔的文件到Perl中的數組。我不希望換行符成爲數組的一部分,因爲這些元素是文件名以供稍後閱讀。也就是說,每個元素應該是「foo」而不是「foo \ n」。我已經在過去使用的堆棧溢出問題Read a file into an array using PerlNewline Delimited Input提倡的方法,成功地做到了這一點。讀換行符在Perl

我的代碼是:

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

我的文件 '測試' 是:

a 
b 
c 
d 
e 

我的預期輸出是:

a b 

我的實際輸出爲

a 
b 

我真的不明白我做錯了什麼。我如何將這些文件讀入數組?

回答

4

這裏是我一般從文件中讀取。

open (my $in, "<", "test") or die $!; 
my @arr; 

while (my $line = <$in>) { 
    chomp $line; 
    push @arr, $line; 
} 

close ($in); 

chomp將從行讀取中刪除換行符。您還應該使用open的三參數版本。

0

一個不太詳細的選項是使用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

0
  • 將文件路徑置於其自己的變量中,以便可以很容易地更改 。
  • 使用3參數打開。
  • 測試全部打開,打印,並關閉了成功,如果不是,打印錯誤和文件名。

嘗試:

#!/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";