user3527124
user3527124

Reputation: 63

search and replace a pattern in a line in perl

I need a help with regular expression:

I have a file which has a line like this:

label   9   { V { some_text ; } W { some_text;} } #12345.

now the condition is, if the line has label 9, I have to replace it with NOP (everything else on the line should remain the same) and I can't seem to figure out why

This is what I did (only releveant portion of the code):

my $cur_line = $_;


if($cur_line =~ s/label\s+9/)

{

       $cur_line =~ s/label\s+9/NOP/;
       print "$cur_line";

}

Thanks!

Upvotes: 0

Views: 66

Answers (1)

toolic
toolic

Reputation: 62037

Your code did not compile for me untill I changed:

if($cur_line =~ s/label\s+9/)

to:

if($cur_line =~ /label\s+9/)

Note the s/. Then, it performed the substitution you desire.

You can simplify this as:

my $cur_line = $_;
if ($cur_line =~ s/label\s+9/NOP/) {
    print $cur_line;
}

Upvotes: 3

Related Questions