2010-10-26 69 views
1

我有一個文件,它看起來像:perl的替代多行

<QUERY name="Secondary"> 
      <SQLStmt>select * from my_tb; 
      </SQLStmt> 
<QUERY name="primary"> 
      <SQLStmt>select * from my_tb; 
      </SQLStmt> 

<QUERY name="last"> 
      <SQLStmt>select * from my_tb; 
      </SQLStmt> 

我需要與其他一些SQLStmnts和查詢的名字,我從收到命令行來替代SQLStmnts。

如何使用條件進行匹配和替換?

$qury_nm=shift; 
$sqlstmt=shift; 
undef $/; 
if(/<QUERY name="$qury_nm">(.*)<SQLStmt>(.*)<\SQLStmt>/) 
{ 
    #need help here!! 
    substitute the matched qury_nms SQLStmt wth the $sqlstmt and write it into the same file... 
} 
+0

http://codepad.org/ekwVuA5U 請參閱此鏈接以獲得更好的視圖 – Nachikethas 2010-10-26 13:31:20

+0

我不認爲「推」命令做你認爲它的作用:-) – 2010-10-26 14:04:48

+0

ooh ..it應該轉移而不是推... 改變了:) – Nachikethas 2010-10-26 14:37:16

回答

0

這裏有很長的路要走:

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

my $qury_nm = 'primary'; 
my $sqlstmt = 'SELECT col1,col2 FROM table2'; 
undef $/; 
my $str = <DATA>; 

$str =~ s!(<QUERY name="$qury_nm">.*?<SQLStmt>).*?(</SQLStmt>)!$1$sqlstmt$2!s; 
say $str; 

__DATA__ 
<QUERY name="Secondary"> 
      <SQLStmt>select * from my_tb; 
      </SQLStmt> 
<QUERY name="primary"> 
      <SQLStmt>select * from my_tb; 
      </SQLStmt> 

<QUERY name="last"> 
      <SQLStmt>select * from my_tb; 
      </SQLStmt> 

輸出:

<QUERY name="Secondary"> 
      <SQLStmt>select * from my_tb; 
      </SQLStmt> 
<QUERY name="primary"> 
      <SQLStmt>SELECT col1,col2 FROM table2</SQLStmt> 

<QUERY name="last"> 
      <SQLStmt>select * from my_tb; 
      </SQLStmt>