Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

#!/usr/bin/perl use strict; use warnings; while(<DATA>){ $_ =~ s/<p>/<con><p>/g; $_ =~ s/<\/p>/<\/p><\/con>/g; print $_; } __DATA__ <p>This is param1</p> <p>This is second para</p> <p>this is param3</p>
How to replace only the first <p> with <con><p> and last </p> with
</p></con><code> <br/> Now all the <code><p>
tag is substituted.

Replies are listed 'Best First'.
Re: search and replace
by keszler (Priest) on Nov 04, 2009 at 16:05 UTC
    #!/usr/bin/perl use strict; use warnings; print '<con>'; my $out; while(<DATA>){ $out .= $_; } chomp($out); print "$out</con>\n"; __DATA__ <p>This is param1</p> <p>This is second para</p> <p>this is param3</p>

    Do you mean replace the first p-tag in all DATA, or the first p-tag on each line? Ditto for last.

    If you did mean by line, step 1 is to drop the 'g' from your regexes.

Re: search and replace
by bichonfrise74 (Vicar) on Nov 04, 2009 at 17:46 UTC
    Is this what you want?
    #!/usr/bin/perl use strict; while (<DATA>) { my ($word) = /\>(.*)\</; print "<con><p>$word</p></con><code> <br/>\n"; } __DATA__ <p>This is param1</p> <p>This is second para</p> <p>this is param3</p>
      <p>This is param1</p> <p>This is second para</p> <p>this is param3</p>
      The output should be
      <con><p>This is param1</p> <p>This is second para</p> <p>this is param3</p></con>
      Please tell me how to get the output this way
        printf("<con>%s</con>", do { local $/; <DATA> } ); __DATA__ <p>This is param1</p> <p>This is second para</p> <p>this is param3</p>

        Facetiousness aside, the DATA iteration isn't working the way you think/want and though there are plenty of tricks to get it to do what you're after in this context it's not a good practice; you should parse/edit XML with an XML parser/writer. XML::Twig and XML::LibXML are (generally) the favorites around these parts.