Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl code to find and substitute a pattern

Tags:

regex

perl

output        [15:0] pin;                
output         [1:0] en;                
input          [6:0] dddr;            
input          [6:0] dbg;

replace this with

16 : pin : output;                         
2 : en : output;                
7 : dddr : input;            
7 : dbg :input;

I tried this code after opening the file and stored it in var. but i am not able to filter it like above

if ($var =~ /(\w+)\[(\d+)\:/) {  
    print "word=$1 number=$2\n";
}

//i am trying to add : in middle of the columns also

like image 576
flash Avatar asked Nov 22 '25 15:11

flash


2 Answers

You are missing the whitespace after the word characters in your pattern.

(\w+ )       \[(\d+):
      VVVVVVVV
output        [15:0] pin;                

This is easily fixed. Add it into the pattern in between, like so:

use strict;
use warnings;
use feature 'say';

while (my $line = <DATA>) {
    if ($line =~ /(\w+)\s+\[(\d+)\:/) {
        say "word=$1 number=$2";
    }
}

__DATA__
output        [15:0] pin;
output         [1:0] en;
input          [6:0] dddr;
input          [6:0] dbg;

This produces:

word=output number=15
word=output number=1
word=input number=6
word=input number=6

To get to your desired output, you'll have to refine the pattern and probably do some incrementing too.

like image 90
simbabque Avatar answered Nov 24 '25 11:11

simbabque


You are not taking account of the whitespace between (\w+) and the (\d+) parts of your regex.

while (<DATA>)
{
    if ( /(\w+)\s+\[(\d+)\:/) {  
        print "word=$1 number=$2\n";
    }
}

__DATA__
output        [15:0] pin;                
output         [1:0] en;                
input          [6:0] dddr;            
input          [6:0] dbg;

That outputs this

word=output number=15
word=output number=1
word=input number=6
word=input number=6

To get to your close to your final requirement, the regex can be expanded to match the other parts you need, as follows

while (<DATA>)
{
    if ( /(\w+)\s+\[(\d+)\:\d+\]\s+(.*);/) {  
        print "$2 : $3 : $1\n";
    }
}

__DATA__
output        [15:0] pin;                
output         [1:0] en;                
input          [6:0] dddr;            
input          [6:0] dbg;

which outputs this

15 : pin : output
1 : en : output
6 : dddr : input
6 : dbg : input

Not sure how you calculate the value for the first column. It appears to be the number field + 1. Is that correct?

like image 24
pmqs Avatar answered Nov 24 '25 11:11

pmqs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!