2015-12-10 48 views
-2

我在尋求一些有關此代碼效率的反饋,以及如何從@FilesToUse數組中移除符合條件的文件。用perl檢查文本文件的內容

我將一個目錄中的所有文件加載到@FilesToUse數組中。然後我需要檢查每個文件,看看第7行是否顯示'BATCH',如果它是我想移動文件,然後從@FilesToUse數組中刪除文件名,所以當我稍後使用該數組時沒有BATCH文件名在裏面。我希望我明確提出這個問題。

文本文件大約是10Mb,我通常每天要處理2個文件。

在此先感謝您的幫助。

#Loop thru the files that were found and delete the one that is BATCH 

     foreach $FileToUse (@FilesToUse) #Loop at the file level 
     { 

open (FH, $TheInputDir . $FileToUse) or $MailMsg = $MailMsg . "ERROR: Could not open input file: $FileToUse \n"; 

      while (<FH>)      # Loop at the line level within each file 
      { 
      $TheLine = $_; 
      chomp($TheLine); 
      $LineCnt++; 

      if ($LineCnt == 7 and substr($TheLine, 1, 6) =~ /BATCH/) { 

       move("$TheInputDir$FileToUse", "$TheBatchMoveDir") 
        or $MoveFail = 1; 

       if ($MoveFail == 1) { 
        $MailMsg = $MailMsg 
         . "ERROR: Failed to move $FileToUse to Batch folder!\n"; 
       } 
       else { 
        $MailMsg 
         = $MailMsg . "Moved BATCH file $FileToUse to Batch folder\n"; 
       } 
      } 

      last if $. == 7; 
      } 
     } 
+0

輸入文件的示例也很有用。 –

+0

而不是刪除一個元素,如果它從來沒有被添加到「@ FilesToUse」中,它會不會更好? –

+0

另外,你可以爲這個問題創建一個[mcve]嗎? –

回答

-1

我會收拾語義:

  $LineCnt = $.; 

     if ($LineCnt == 7) { 
      close FH; 

      if (substr($TheLine, 1, 6) =~ /BATCH/) { 

       move("$TheInputDir$FileToUse", "$TheBatchMoveDir") 
        or $MoveFail = 1; 

       if ($MoveFail == 1) { 
        $MailMsg = $MailMsg 
        . "ERROR: Failed to move $FileToUse to Batch folder!\n"; 
       } 
       else { 
        $MailMsg 
        = $MailMsg . "Moved BATCH file $FileToUse to Batch folder\n"; 
       } 
      } 

      last; 
     } 
0

如何從@FilesToUse陣列

我們可以從一個陣列splice刪除元素刪除符合條件的文件,但我們需要這個數組索引。
你可以外環改爲

 foreach $findex (-$#FilesToUse..0) #Loop at the file level 
     { 
      $FileToUse = $FilesToUse[-$findex]; 

,並插入

   splice @FilesToUse, -$findex, 1; 

要刪除的文件元素。
(數組從最後到第一個元素進行處理,以避免刪除索引時出現「缺失元素綜合症」 - 另請參閱How do I completely remove an element from an array?