regexperl

Replace $variable which changes every iteration in while loop


I have two input files: filea and fileb. In filea, I have a string $pc_count$, where in fileb, there are numbers and strings. I have to search numbers in fileb and replace $pc_count$ in filea.

I have tried the code below, but the first value of fileb is repeated ($pc_count$) every time.

open (IN_FILE, "<filea") or die "Please provide an correct file path\n";
open (IN_FILE1, "<fileb") or die "Please provide an correct file path\n";
my $i = 0;
while (<IN_FILE>) {
        if($_ =~ /\$pc_count\$/) {
                my $line = $_;
                while (<IN_FILE1>) {

                        if($_ =~ /([a-z0-9-]+)[\s]+/) {
                                my $first = $1; 
                                $line =~ s/\$pc_count\$/$first/;
                                #print OUT_FILE("$line");
                                print $line;

                        }

                }

        }
        #print OUT_FILE("$_");
}
close IN_FILE;
close IN_FILE1;

filea

case(pc)
    'h$pc_count$ : $display("checkdata string %s ",pc_string);
endcase

fileb

fe0000
fe0001
fe0002
fe0003
..
..
..

Result:

case(pc)
    'hfe000 : $display("checkdata string %s ",pc_string);
    'hfe000 : $display("checkdata string %s ",pc_string);
    'hfe000 : $display("checkdata string %s ",pc_string);
    'hfe000 : $display("checkdata string %s ",pc_string);
    ..
    ..
    ..
    ..  
endcase

Solution

  • After your first substitution, $line is changed, and it no longer has the string $pc_count$. One way to fix this is to keep a copy of the original line in another variable ($line2):

    use warnings;
    use strict;
    
    open (IN_FILE, "<filea") or die "Please provide an correct file path\n";
    open (IN_FILE1, "<fileb") or die "Please provide an correct file path\n";
    my $i = 0;
    
    while (<IN_FILE>) {
            if ($_ =~ /\$pc_count\$/) {
                    my $line = $_;
                    while (<IN_FILE1>) {
                            my $line2 = $line;
                            if ($_ =~ /([a-z0-9-]+)[\s]+/) {
                                    my $first = $1; 
                                    $line2 =~ s/\$pc_count\$/$first/;
                                    print $line2;
                            }
                    }
            }
            #print OUT_FILE("$_");
    }
    close IN_FILE;
    close IN_FILE1;
    

    Output:

    'hfe0000 : $display("checkdata string %s ",pc_string);
    'hfe0001 : $display("checkdata string %s ",pc_string);
    'hfe0002 : $display("checkdata string %s ",pc_string);
    'hfe0003 : $display("checkdata string %s ",pc_string);