ADBlock is blocking some content on the site

ADBlock errore

To replace text between tags that span multiple lines by another text in perl

StackOverflow https://stackoverflow.com/questions/13216703


I need to replace a multiline text between the tags(<stats>...</stats>) in a file with another multiline text from other file in Perl. I'm using search and replace functions but not working currently. If both the start tag and end tag are in the same line then I am able to replace them else its not replacing. For Ex,in destination file:


    <stat type="string" value="a" />
    <stat type="string" value="b" />
    <stat type="string" value="c" />
    <stat type="string" value="d" />


A part of my code snippet is as follows:

my $replacetext="<stats>"."@lines"."</stats>";
my $searchtext="<stats>.*</stats>";

# Here @file_lines is the array containing destination file and  @lines is the array containing source file.

foreach (@file_lines) 
      $_=~ s/$searchtext/$replacetext/g;

'.*' work only if start tag and end tag are in same line.

No correct solution


It is not ok to parse HTML/XML with regexes. As @mu mentioned, try using an XML parser - you can achieve what you want with XML::Simple for example.

Have a look at the tutorial XML for Perl developers, Part 1: XML plus Perl -- simply magic

It is more than you need, but will offer you a good introduction to working with XMLs in Perl

Do not use regular expressions to parse XML. Use an XML parser.

An example using XML::XSH2, a wrapper around XML::LibXML:

my $source ;
$source = { open my $SOURCE, '<', 'source.xml' or die $! ; local $/ ; <$SOURCE> } ;
open destination.xml ;
for //stats {
    rm ./* ;
    insert chunk $source into . ;
save :b ;

Although using XML libraries is generally the right thing to do, you can still do this in a quick-and-dirty manner if the file isn't too large and you don't want the overhead of actually parsing and traversing the XML (only small changes required, for instance). However, doing this is quite brittle

my $joined_file = join "\n", @file_lines;          # one long multi-line string
$joined_file =~ s/$searchtext/$replacetext/sg;     # s means multi-line
my @updated_file_lines = split /\n/, $joined_file; # result

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow