Click here to Skip to main content
15,615,469 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm newbie to Perl,i want to close the book-part tag at the end of each chapter and i have n chapters,i.e)book-part should be close before the next chapter begin,
i tried the below code but it couldn't show any changes
if($str =~ /<book-part book-part-type="chapter" id="chapter\d+">((?:(?!<\/?book-part book-part-type="chapter" id="chapter\d+">).)*)(?=<book-part book-part-type="chapter" id="chapter\d+">)/sgi)
    $str .="<book-part>";

each chapter begin with this below tag
<book-part book-part-type="chapter" book-part-number="\d+" id="chapter\d+">

and i want to generate a output like this
<book-part book-part-type="chapter" book-part-number="2" id="chapter2"

is a first chapter's closing tag and
<book-part book-part-type>
is a second chapter's opening.
plz any one help me to solve my problem.......
Updated 5-Jan-12 19:49pm
Andreas Gieriet 6-Jan-12 7:00am    
I don't get your exact problem.Is it as follows:
- you have an array of input lines from an XML file(?)
- the input XML file is not conformant, since the closing tags are missing?
You need to make the XML conformant?

Please clarify.

1 solution

The issue seems to be, that your "if" condition will never be met (wrong assumptions and/or too complicated?).

Note: XML is a free format, i.e. the content may be spread over multiple lines.

If you need to modify the whole XML file, then it's best to slurp in the whole file into one string and process that data at once.

Slurp from STDIN:
my $sep= $/;
undef $/;
my $buf = <stdin>;
$/ = $sep;</stdin>

Process the buffer:
$buf =~ s%(<book-part\s*[^/])%</book-part>\1%g;

Note: for better legibility, I've chosen % as regex separator.

The above mentioned solution is not the whole solution since it does not manage the first start tag nor the trailing closing tag properly. I need to see the original file (or the schema). See also my comment to your question.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900