Abhishek Abhishek - 1 year ago 60
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

for all the occurrence it matches in a file


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 Source

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:

use strict;
use warnings;

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download