2014-03-12 26 views
1

我想要一個腳本來更新輸入文件中的變量。 RegEx匹配,但不會執行替換。我究竟做錯了什麼。在外部文件中用RegEX替換文本Perl

sub updateInputDeck { 
my $powerLevel = shift; 
my $file = $outputFiles{input}; 
open INPUTFILE,"<",$file or die "Cannot open file $file $!\n"; 
while (<INPUTFILE>) { 
    if (s/((?<=\s{3}RP\s{2}=\s{2})\d+)/$powerLevel/) { 
     print $_; 
     print "Updating Input File for Power Level: $powerLevel"; 
    } 
} 
close INPUTFILE; 
} 

UPDATE

我試圖更新該文件指出,在該文件句柄。我只能通過打印聲明來做到這一點。如果是這種情況,我只想重印一行。那可能嗎?

回答

3

您可以使用Perl的in-place editing

sub updateInputDeck { 
    my $powerLevel = shift; 
    my $file = $outputFiles{input}; 

    local @ARGV = ($file); 
    local $^I = '.bac'; 
    while(<>){ 
     s/((?<=\s{3}RP\s{2}=\s{2})\d+)/$powerLevel/; 
     print; 
    } 

    #unlink "$file$^I" or die "Can't delete backup"; 

    return; 
} 

另外請注意,您使用的全球$outputFiles{input}作爲參數傳遞給你的函數是一個不良作風的做法。而是將它作爲參數傳遞給你的函數。

+0

我其實比我自己更喜歡這個答案。 :) 謝謝! – sgauria

1

我認爲你必須做2次。首先將整個文件讀取到一個數組中,在本地進行編輯並將整個文件寫回,並覆蓋原始文件。

open INPUTFILE,"<$file" or die "Cannot open file $file $!\n"; 
my @lines = <INPUTFILE>; # Read in entire file. 
close INPUTFILE; 

open INPUTFILE,">$file" or die "Cannot open file $file $!\n"; 
foreach $line (@lines) { 
    $line =~ s/((?<=\s{3}RP\s{2}=\s{2})\d+)/$powerLevel/; 
    print INPUTFILE $line; 
} 
close INPUTFILE; 
+0

@sguaria正是醫生訂購的東西 – TheCodeNovice

+0

@ Miller的答案更有記憶效率,如果你必須處理非常大的文件。我想這個答案更容易理解。 – sgauria