I have a file which looks like:
<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>
I need to substitute the SQLStmnts with some other SQLStmnts and Query name I received from commandline.
How can I use a condition to match and subs开发者_StackOverflow社区titute?
$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...
}
XML is not a regular language. You should not treat it as such. Use one of the fine XML parsers available for Perl. A good way might be to use XML::Twig. Here is a tutorial: http://www.xml.com/pub/a/2001/03/21/xmltwig.html.
Here is a way to go :
#!/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>
Output:
<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>
精彩评论