2014-05-14 36 views
1

我有5個文件在不同的目錄中。我從所有文件中提取數據並將其作爲新文件。perl:輸入多個文件作爲數組

注意:將每個文件作爲數組輸入並通過for each循環爲每個文件提取數據。我希望把它作爲一個for循環取文件和處理,其餘

對於文件1我用

foreach (@file) 
{ 
    my @temp = split(/\t/, trim($_)); 
    push(@output, $temp[0] . "\t" . $temp[1] . "\n"); 
} 

foreach(uniq(@output)) 
{ 
    print $OUTPUTFILE $_; 
} 

我這樣做五次處理五檔。誰能幫我對如何使簡單

+0

cat file1 file2 file3 | do_things_with_perl.pl –

+0

@JohnC,我不想用貓。我需要在數組 – sara

+1

中執行該操作。您可以將該代碼放入循環中。 –

回答

1

只需敷在外環,遍歷所有五個文件:

for my $file (@five_files) { 

    open my $fh, '<', $file or die "Unable to open $file: $!"; 
    my @file = <$fh>; 

    foreach (@file) { 
     my @temp = split(/\t/, trim($_)); 
     push(@output, $temp[0] . "\t" . $temp[1] . "\n"); 
    } 

    foreach(uniq(@output)) { 
     print $OUTPUTFILE $_; 
    } 
} 

由於您希望在短短的前兩個元素@temp,在foreach @file迴路可以簡化爲:

my @temp = split /\t/, trim($_), 2; 
push @output, @temp, "\n" ; 
+0

Zaid,我的@temp = split/\ t /,trim($ _),2;單獨提取前兩行而不是前兩個列元素 – sara

0

如果你用加入不上不下的@file陣列事情簡單化。 然後,您可以將其分割並處理列表。 例如:如果您在文件名中有空格,雖然

!/usr/bin/perl 

my @file = ("file1\tfile3 ","file1\tfile3\tfile3 ","file2"); # Some test data. 

my $in = join "\t", @file; # Make one string. 
my @temp = split(" ", $in); # Split it on whitespace. 


# Did it work? 
foreach(@temp) 
{ 
    print "($_)\n"; # use() to see if we have any white spaces. 
} 

可能是一個問題!