Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

replace at the begining

by Anonymous Monk
on Aug 20, 2009 at 10:18 UTC ( #790046=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

#!/usr/bin/perl while(<DATA>){ s/p\sclass=/\<p\\sclass=/g; print $_; } __DATA__ p class="Hi"> <p class="new">
How to search for the string where (p class=) and if before the string if character '<' doesnot exists should be replaced with <. The output should be
<p class="Hi"> <p class="new">

Replies are listed 'Best First'.
Re: replace at the begining
by ashish.kvarma (Monk) on Aug 20, 2009 at 12:37 UTC
    Another simple solution could be (without using look-behind)
      #!/usr/bin/perl while(<DATA>){ s/(?<!<)p\sclass=/<p class=/; print $_; } __DATA__ <p class="Hi">Hello <p class="new">How r u
      The above output should look like
      <p class="Hi"\>Hello <p class="new"\>How r u
Re: replace at the begining
by Melly (Hermit) on Aug 20, 2009 at 10:48 UTC

    The easiest way is to use a negative class (as noted below by others, this will only work when the error isn't the first thing on the line).


    Alternatively, use a negative look-behind - (?<!foo):

    s/(?<!<)p\sclass=/<p class=/;

    Fixed the code - no \s as a replacement

    map{$a=1-$_/10;map{$d=$a;$e=$b=$_/20-2;map{($d,$e)=(2*$d*$e+$a,$e**2 -$d**2+$b);$c=$d**2+$e**2>4?$d=8:_}1..50;print$c}0..59;print$/}0..20
    Tom Melly, pm (at) cursingmaggot (stop) co (stop) uk

      The first solution doesn't work, e.g. when the problem is at the beginning of a line.

      The negative look-behind does, but character classes don't belong in the replacement string- you can just type the space:

      s/(?<!<)p\sclass=/<p class=/;
      You can't use character classes like \s in the replace string, only in the search pattern.
      Using of space as '\s' why s is displayed between p and class
      <psclass="Hi"> <p class="new">
        My mistake - \s means a whitespace character, which can be several things (a space, a tab, etc.). So it makes no sense as a substitution character (of the various options, which should perl use?).
        map{$a=1-$_/10;map{$d=$a;$e=$b=$_/20-2;map{($d,$e)=(2*$d*$e+$a,$e**2 -$d**2+$b);$c=$d**2+$e**2>4?$d=8:_}1..50;print$c}0..59;print$/}0..20
        Tom Melly, pm (at) cursingmaggot (stop) co (stop) uk
Re: replace at the begining
by sanku (Beadle) on Aug 21, 2009 at 10:02 UTC
    hi, The following replacement will be work fine.
    while($line=<DATA>){ $line=~s/p\sclass=/<p class=/g; print $line; }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://790046]
Approved by Bloodnok
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2018-05-26 05:22 GMT
Find Nodes?
    Voting Booth?