2009-07-03 88 views
0

我是一個Perl的小白用戶試圖讓我的工作儘快完成,所以我可以按時回家今天:)的Perl - 打印下一行

基本上我需要打印的空行的下一行文本文件。

以下是我到目前爲止的內容。它可以很好地找到空白行。現在我只需要打印下一行。

open (FOUT, '>>result.txt'); 

die "File is not available" unless (@ARGV ==1); 

open (FIN, $ARGV[0]) or die "Cannot open $ARGV[0]: $!\n"; 

@rawData=<FIN>; 
$count = 0; 

foreach $LineVar (@rawData) 
    { 
     if($_ = ~/^\s*$/) 
     { 
      print "blank line \n"; 
        #I need something HERE!! 

     } 
     print "$count \n"; 
     $count++; 
    } 
close (FOUT); 
close (FIN); 

多謝:)

+0

將整個文件寫入內存是否明智?所示練習不是100%必要的。 – 2009-07-03 15:52:09

+0

即使你想使用數組,它甚至不需要1%。看看Tie :: File(自從5.8以來的核心部分,大約在2002年)。 – 2009-07-03 16:56:41

+0

文件不是那麼大,但絕對不是個好主意。我會看看Tie :: File :)謝謝 – b1gtuna 2009-07-03 18:02:16

回答

5
open (FOUT, '>>result.txt'); 

die "File is not available" unless (@ARGV ==1); 

open (FIN, $ARGV[0]) or die "Cannot open $ARGV[0]: $!\n"; 

$count = 0; 

while(<FIN>) 
{ 
    if($_ = ~/^\s*$/) 
    { 
      print "blank line \n"; 
      count++; 
      <FIN>; 
      print $_; 

    } 
    print "$count \n"; 
    $count++; 
} 
close (FOUT); 
close (FIN); 
  • 不讀整個文件到@rawData保存記憶中,特別是在大文件的情況下...

  • <FIN>作爲命令讀取下一行到$ _

  • print ;本身是print $_;的代名詞(雖然我去了更明確Variant該時間......

0

添加一個變量如$ lastLineWasBlank,並在每個循環的結尾設置。

if ($lastLineWasBlank) 
    { 
    print "blank line\n" . $LineVar; 
    } 

類似的東西。 :-)

1

我是這樣的,但可能還有其他的方法來做到這一點:

for (my $i = 0 ; $i < @rawData ; $i++){ 
    if ($rawData[$i] =~ /^\s*$/){ 
     print $rawData[$i + 1] ; ## plus check this is not null 
    } 
} 

J.

+0

這是不是隻打印所有非空行? – 2009-07-03 15:19:35

2

在闡述羅恩野人的解決方案:

foreach $LineVar (@rawData) 
    { 
     if ($lastLineWasBlank) 
      { 
       print $LineVar; 
       $lastLineWasBlank = 0; 
      } 
     if($LineVar =~ /^\s*$/) 
     { 
       print "blank line \n"; 
        #I need something HERE!! 
       $lastLineWasBlank = 1; 
     } 
     print "$count \n"; 
     $count++; 
    } 
0
sh> perl -ne 'if ($b) { print }; if ($b = !/\S/) { ++$c }; END { print $c,"\n" }' 

添加輸入文件名(S)根據自己的喜好。