2013-05-10 65 views
0

我試圖寫一個Perl腳本,將改變輸入如何合併2行perl腳本

(name 
    (type .... 
) 
) 

到輸出

(name (type ...)) 

即所有這些匹配()的行都被合併成一行,我想更新原始文件本身。

在此先感謝

+1

這是4行。看起來你只是想將換行符轉換爲空格。 – jordanm 2013-05-10 20:15:35

+0

你可能想看看核心模塊[Text :: Balanced](http://perldoc.perl.org/Text/Balanced.html),雖然它可能是目前的問題矯枉過正。 – 2013-05-10 20:31:31

+0

我相信我的回答應該幫助你。 – 2013-05-10 21:06:02

回答

0

是否保證((..))語法?如果是的話我建議合併整個事情成一條線,然後根據分裂)(S。

my $line = ""; 
while(<DATA>) 
{ 
$_ =~ s= +$==g; # remove end spaces. 
$line .= $_; 
} 
$line =~ s=\n==g; 
my @lines = split /\)\(/,$line; 
my $resulttext = join ")\n(", @lines; 
print $resulttext; 



__END__ 

(name 
(type ....  
) 
) 
(name2 
    (type2 .... 
) 
)  
(name3 
(type3 .... 
) 
) 
1
use strict; 
use warnings; 

my $file="t.txt"; #or shift (ARGV); for command line input 
my $new_format=undef; 

open READ, $file; 
local $/=undef; #says to read to end of file 

$new_format=<READ>; 
$new_format=~ s/\n//g; #replaces all newline characters with nothing, aka removes all \n 

close(READ); 

open WRITE, ">$file"; #open for writing (overwrites) 
print WRITE $new_format; 
close WRITE; 

這工作,假設整個文件是一個大的表現。作爲參考,以去除所有的空格,使用$new_format=~ s/\s//g;而不是$new_format=~ s/\n//g;。它可以很容易地修改以解釋多個表達式。所有人都必須重新定義$/是用來分隔表達式的任何東西(例如,如果只是一個空行:local $/ = /^\s+$/; )並將所有內容放入while循環中對於每次迭代,將字符串推入數組,並在完成文件處理後,將數組內容寫入文件格式,你需要。

0

這裏的另一種選擇:

use strict; 
use warnings; 

while (<>) { 
    chomp unless /^\)/; 
    print; 
} 

用法:perl script.pl inFile [>outFile]

的樣本數據:

(name 
    (type .... 
) 
) 
(name_a 
    (type_a .... 
) 
) 
(name_b 
    (type_b .... 
) 
) 

輸出:

(name (type .... ) ) 
(name_a (type_a .... ) ) 
(name_b (type_b .... ) ) 

的腳本刪除輸入REC ord分隔符,除非行讀取包含最後一個關閉權限paren(匹配該行上的第一個字符)。

希望這會有所幫助!