Perl not subtituting strings with newline

Viewed 73

I have this problem with subtituting characters on perl. My goal is to remove every "." and "-" on my xml. It goes well with the first 4 tags, but it doesnt remove the "." and "-" on the description tag that has a newline on its content.

This is my code:

 />([^\000]*?)</g;
 $lastp = $1;
 $lastp =~ s/[\.|\-]*?//g;
 $_ =~ s/(>)[^\000]*?(<)/$1$lastp$2/g; 

This is my sample data:

   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>.44.95......</price>
      <publish_date>200.0-10-
      01.</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>

And here is my output:

 <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>4495</price>
      <publish_date>200.0-10-
      01.</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
  </book>
1 Answers

Would you please try the following:

#!/usr/bin/perl

use strict;
use warnings;

$_ =<<'EOS';
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>.44.95......</price>
      <publish_date>200.0-10-
      01.</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
EOS

s/(?<=>)[^<]+/ my $s = $&; $s =~ s#[-.]##g; $s /ge;

print;

Output:

   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>4495</price>
      <publish_date>200010
      01</publish_date>
      <description>An indepth look at creating applications
      with XML</description>
   </book>
  • The substitution processes the whole lines as a string at once.
  • The pattern (?<=>)[^<]+ matches a string between tags: (?<=>) is a zero width lookbehind assertion of leading > and [^<]+ matches the following sequence of any characters except for <. Then the variable $& is assigned to the matched substring.
  • my $s = $&; $s =~ s#[-.]##g; $s removes - and . from the matched substring. Then the modified string $s is used as the replacement of the s/pattern/replacement/ operator thanks to the e option.
Related