Abhishek Abhishek - 2 months ago 6
Perl Question

matches happen but replacement not happening

the line that I want to replace:

1.my_type NEW{ 2} my type
2.my_type TEST{ 0} my type


my expected output:

1. my_type NEW{ 0x02} my type
2. my_type TEST{ 0x00} my type


I want to replace
NEW{2}
with
NEW{0x02}
and
NEW{0}
with
NEW{0x00}


for all the occurrence it matches in a file

my_code:

while (<DATA>)
{
if (/NEW\s+[{2}]\d+/)
{
s/NEW{ 2}/NEW{ 0x02}/ ;
}
elsif (/NEW\s+[{0}]\d+/)
{
s/NEW{ 0}/NEW{ 0x00}/ ;
}
}


why the replacement is not happening..?

Answer

There is no reason to use multiple substitutions you can do it with one. Try this

s/NEW *\{ *([02])* \}/NEW{ 0x0$1}/;

and you don't need the conditionals. So something like that should do it:

#!/usr/bin/perl
use strict;
use warnings;

while (<DATA>) {
    s/NEW *\{ *([02]) *\}/NEW{ 0x0$1}/;
    # do something with $_ here, e.g.:
    print $_;
}

__DATA__
1.my_type   NEW{ 2} my type
2.my_type   NEW{ 0} my type

Essentially, the substitution operator handles the conditionals for you. It will perform the substitution only if the regex matches.