2015-07-02 93 views
-2

我想在一個巨大的文件中替換字符串包含許多行。如何使用散列將「x」和「y」換成「y」和「x」

FILE.TXT

line1: "X" = 5.5; "Y" = 7.5; "Z" = 9.0; 
line2: "V" = 66; "Y" = 3; "U" = 11.0; 

等等...

替身哈希值(%rhash)包含地圖信息

$rhash{"X"} = "Y"; 
$rhash{"Y"} = "X"; 
$rhash{"Z"} = "A"; 
$rhash{"V"} = "B"; 
$rhash{"U"} = "C"; 

當我試圖

while (($cur, $cng) = each(%rhash)) { 
    $line =~ s/\Q"$cur"\E/\"$cng\"/g; 
} 

第1行是int變化Ø無論

"X" = 5.5; "X" = 7.5; "A" = 9.0; 

"Y" = 5.5; "Y" = 7.5; "A" = 9.0; 

但正確的改變是

"Y" = 5.5; "X" = 7.5; "A" = 9.0; 

我怎麼能做到這一點..

感謝您的幫助......

+0

注:哈希鍵不僅是文字。鍵可以是任何匹配的模式(\ S +) – AKS

回答

1

你需要改變他們simul taneously。最簡單的方法是使一種化合物可執行正則表達式,並期待基於什麼是匹配的替代:

$re = join("|", map { "\\Q$_\\E" } keys(%rhash)); 
$str =~ s/$re/$rhash{$&}/ge; 

當然,這僅用於更換的鍵是文字,而沒有正則表達式的語義工作。

編輯如果你需要的東西像$rhash{"\d+"} = "NUMBER",這應該工作:

sub find_replacement { 
    my ($match, $patterns, $rhash) = @_; 
    foreach my $pattern (@$patterns) { 
    if ($match =~ s/$pattern/$$rhash{$pattern}/e) { 
     return $match; 
    } 
    } 
    die "impossible!"; 
} 

my @patterns = keys(%rhash); 
my $re = join("|", @patterns); 

$str =~ s/$re/find_replacement($&, \@patterns, \%rhash)/ge; 
+0

謝謝..鍵不是文字,並有正則表達式語義 – AKS

+0

謝謝...您的建議解決了問題.. – AKS