2013-12-17 30 views
0

我是perl的新手,並且正在嘗試在perl tk中編寫程序。我大部分都是這樣,但似乎無法得到最後的結果。如何在perl中的兩個已知行之間搜索多行txt文件

我在一個txt文件,看起來像這樣的閱讀...

display ("Blue") 
.... 
.... 
.... 
.... 
display ("Yellow") 
.... 
bobby 
.... 
.... 
display ("Red") 
.... 
.... and so on 

的「......」 S是我真的不關心數據的部分,但我必須通過搜索找到「博比」。

我已經構建了一個數組,用於存儲所有顯示在其中的行。即@array。我想在原始.txt文件中的每個「顯示」行之間搜索「bobby」,並輸出它上面的任何顯示行。

對於上面的例子中,我想

顯示器的輸出(「黃色」)

我想我需要一個while循環所有欲SEACH顯示器之間的區域之間進行迭代。

我的代碼如下所示,顯示了我構建的一些東西。 當輸入完成後按下按鈕時,下面的子程序運行。

#Output Substation ID to Pane 
sub find_substations 
{ 
     #Copy the entry 
my $substation_to_search = $find_ensub->get(); 

#Insert the copied entry into the outptutext_box 
$output_textbox->insert("end", "Substation ID: $substation_to_search\n\n"); 

     open(myfile1, "file and file location"); 
     my @lines = <myfile1>; 
     #Open File and Print all lines with display in it. 
     my @array= grep(/display /,@lines); 
     #Array Size 
     my $size = @array; 
     my $start = $lines[0]; 
     my $stop = $lines[1]; 

    while("$x" < "$size") 
    {  
    if("$start".."$stop") 
    { 
     next if /$start/||/$stop/; 
     if()   
     { 
     $output_textbox->insert("end", "$lines[0]"); 
     }#if stop 
     }#If stop 

    $x++; 
    } 
    #close myfile1; 

}

我一直在閱讀有關的啓動和停止,但不能讓它的工作權利。誰能幫我嗎?起始停止部分的代碼不完整。

+2

對於初學者來說,不要無謂地把引號變量。當你嘗試將它們當作數字處理時,這可能也會讓你咬牙切齒:'「$ x」<「$ size」' –

回答

0

如果我正確理解你的問題,我認爲你已經使問題過於複雜。沒有必要跟蹤邊界(您的$start$end),只有當前值display是。例如:

INFILE:

display ("Blue") 
foo 
bar 
display ("Yellow") 
baz 
bobby 
qux 
display ("Red") 
pop 
bobby 

script.pl:

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

open(my $fh, '<', "./".$ARGV[0]) or die("Cannot open file"); 

my $display; 
while (<$fh>) { 
    $display = $_ if /^display/; 
    print $display if /^bobby$/; 
} 

產量:

$ perl ./script.pl ./infile 
display ("Yellow") 
display ("Red") 
+0

謝謝!我不確定是否有命令來執行上面的操作。完善。隨着一些修改它完美的作品。 – Spartakus

相關問題