我有兩個輸入檔案:filea和fileb. 在 中filea,我有一個字串$pc_count$,其中fileb,有數字和字串。我在尋找數fileb和替換$pc_count$的filea。
我已經嘗試了下面的代碼,但是每次fileb都重復 ( $pc_count$)的第一個值。
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;
檔案
case(pc)
'h$pc_count$ : $display("checkdata string %s ",pc_string);
endcase
檔案b
fe0000
fe0001
fe0002
fe0003
..
..
..
結果:
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
uj5u.com熱心網友回復:
[我必須先修復您代碼中的語法錯誤,然后才能運行它。請確保您提供給我們可運行的代碼。]
問題是存盤在$line.
您遍歷IN_FILE檔案句柄,直到找到包含$pc_count$. 然后將該行復制$line到內部處理回圈中。
所以第一次你的內部回圈,$line包含:
'h$pc_count$ : $display("checkdata string %s ",pc_string);
幾行之后,您$line使用以下代碼進行更改:
$line =~ s/\$pc_count\$/$first/;
所以$line現在包含:
'hfe000 : $display("checkdata string %s ",pc_string);
下一次回圈時,您將從$line包含以hfe000. 因此,當您嘗試第二次運行替換時,沒有任何變化,因為$line不再包含$pc_count$.
最簡單的解決方法可能根本不改變$line,而是直接列印替換的輸出(并使用/r原始字串不會改變)。
if($_ =~ /([a-z0-9-] )[\s] /) {
my $first = $1;
print $line =~ s/\$pc_count\$/$first/r;
}
其中產生:
'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);
uj5u.com熱心網友回復:
在您的第$line一個替換之后,已更改,并且不再具有字串$pc_count$. 解決此問題的一種方法是將原始行的副本保留在另一個變數 ( $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;
輸出:
'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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/331269.html
