Ria Ria - 1 month ago 9
Perl Question

seach and replace the value inside curely braces

I want to search the value between curly braces for each line in a file
and replace the corresponding value with
0x0 (For e.g. 1-->0x01,7-->0x07)

Initially i was checking with regex (/{(.*?)}/) this regex able to search all the value inside {} braces.
input Data:

abc_def xxxx { 0} xxx
my_new_type new{ 0} my_new_type
c++_programming MY_NPYR{ 1} c++_programming
cprogramming ABCCDDDDRRRRTTTT { 2} cprogramming
perlbook NEW{ 7} xxxxx


code:

#!/usr/bin/perl
use strict;
use warnings;
my $file = 'input.txt';
open my $fh, "<", $file or die "Couldn't open input file: $!";
while (<$fh>)
{

if (/{(.0?)}/)
{
s/0/0x00/;
}
elsif (/{(.1?)}/)
{
s/1/0x01/;
}
elsif (/{(.2?)}/)
{
s/2/0x02/;
}
elsif (/{(.7?)}/)
{
s/7/0x07/;
}

}


any help with explanation would be grateful.

Answer

Save it as script.pl and invoke it as $ perl script.pl input.txt:

use strict;
use warnings;

while (<>) {
    s/\{ (\d+)\}/sprintf('{ 0x%02x}', $1)/ge;
    print;
}

The e regex modifier evaluates the right-hand side as an expression.