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

#!/usr/bin/perl while(<DATA>){ s/(\w*)<$/<p>$1<\/p>/g; print $_; } __DATA__ 9912290449 *In, a law prohibiting in United States went into effect.< < 9912290450
If "<" exists at the end of line, how to convert to </p> and at the begining of the line how to add <p>
<p>9912290449 *In, a law prohibiting in United States went into effect +.</p> <p></p> 9912290450

Replies are listed 'Best First'.
Re: Add at the begining of text
by ig (Vicar) on Aug 31, 2009 at 08:50 UTC

    You almost have it. If you change (\w*) to (.*) your program produces what you want for the test case you have provided. You don't need the /g option on the substitution.

Re: Add at the begining of text
by roboticus (Chancellor) on Aug 31, 2009 at 12:14 UTC

    It looks like you're working with HTML, so you don't need to put the <p> on the next line. You can put it on the same line and it will render just fine. In that case, you can do a simple: s{<$}{</p><p>};

    ...roboticus

      While that is true, it doesn't fit the problem statement the OP described. He needs every line that ends in < to be wrapped in <p></p> tags. How I'd do it:

      while(<>) { if ( s/<$// ) { chomp; print '<p>', $_, "</p>\n"; } else { print; } }
      $,=' ';$\=',';$_=[qw,Just another Perl hacker,];print@$_;
        #!/usr/bin/perl while(<DATA>){ s/(.*)<$/<p>$1<\/p>/g; print $_; } __DATA__ 9912290449 *In, a law prohibiting in United States went into effect.< In, a law prohibiting in United States went into effect.< 9912290450
        Suppose the line is divided into two lines. How to add the start <p> tag at the start of the line. Now the ouptput is
        9912290449 *In, a law prohibiting in United States <p>went into effect.</p> In, a law prohibiting in United States <p>went into effect.</p> 9912290450
        How to add the <p> tag. Where the output should look like
        9912290449 <p>*In, a law prohibiting in United States went into effect.</p> <p>In, a law prohibiting in United States went into effect.</p> 9912290450