2016-12-20 59 views
0

我需要遍歷目錄中的許多文件並將每個文件分成兩部分。我需要保持線條完好(我不能分開一口大小)。我也不能總是假定文件具有相同的行數。我可以使用「分割」功能,但我正在尋找更快的方式來瀏覽我的文件,並避免它生成的標準輸出名稱「xaa」和「xab」。將數組分成兩部分。預定的大小,可能並不總是相等的

最簡單的方法是以指定的大小($ number_of_group_one和$ number_of_group_two)爲數組創建兩個後續子串。我無法找到如何做到這一點。相反,我試圖將這些線條推入不同的陣列 - 填充一條直到一定數量的線條,然後「溢出」到另一個陣列中,直到沒有剩下的線條被推出爲止。但是,這種方法會產生兩個輸出數組,它們的輸入行數都是其數量的兩倍。這裏是我的代碼:

#!/usr/bin/perl 
use warnings; 
use strict; 

my ($directory) = @ARGV; 
my $dir = "$directory"; 
my @arrayoffiles = glob "$dir/*"; 
my @arrayoflines_one; 
my @arrayoflines_two; 
my $counter = 0; 

foreach my $filename(@arrayoffiles){ 
    my @arrayoflines_one; 
    my @arrayoflines_two; 
    my @lines = read_lines($filename); 
    my $NumberofLines = @lines; 
    my $number_of_group_one = int($NumberofLines/2); 
    my $number_of_group_two = ($NumberofLines - $number_of_group_one); 
    foreach my $line (@lines){ 
      $counter++; 
      push (@arrayoflines_one, $line, "\n"); 
      if ($counter == $number_of_group_one){ 
        push (@arrayoflines_two, $line, "\n"); 
      } 
    } 
} 

sub read_lines { 
    my ($file) = @_; 
    open my $in, '<', $file or die $!; 
    local $/ = undef; #slurps the whole file in as one 
    my $content = <$in>; 
    return split /\s/, $content; 
    close $in; 
} 

我希望這是明確的。謝謝你的幫助!

+0

你是說'$ counter == $ number_of_group_one'? – mob

+0

是的!我現在會更新我的帖子。這也改變了輸出。第一個數組是輸入的兩倍,第二個是空的(對於我的大部分輸入文件,並非全部)。 – Rob

回答

3

這是一個很好的用例splice

my @lines = read_lines($filename); 
my @lines1 = splice @lines, 0, @lines/2; 

會把你從行的@lines(約),半入@lines1,消除他們(留下約一半的線)從@lines

+0

拼接工作完美。謝謝暴徒! – Rob

+1

我會用'my @ lines1 = splice @lines,@ lines/2;'。下半場比從上半場開始移除更爲直接。 – ikegami

相關問題