regex - How to change "x" and "y" in a line into "y" and "x" using hash -


i trying replace strings in huge file contains many lines.

file.txt

line1: "x" = 5.5; "y" = 7.5;  "z" = 9.0; line2: "v" = 66;  "y" = 3;  "u" = 11.0; 

so on ...

the replacement hash (%rhash) contains map information

$rhash{"x"} = "y";  $rhash{"y"} = "x";  $rhash{"z"} = "a";  $rhash{"v"} = "b";  $rhash{"u"} = "c"; 

when tried

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

line 1 change either

"x" = 5.5; "x" = 7.5;  "a" = 9.0; 

or

"y" = 5.5; "y" = 7.5;  "a" = 9.0; 

but correct change is

"y" = 5.5; "x" = 7.5;  "a" = 9.0; 

how can achieve this..

thanks help...

you need change them simultaneously. easiest way make compound executable regexp, , substitution based on matched:

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

of course, works if replacement keys literal, , not have regexp semantics.

edit if need things $rhash{"\d+"} = "number", should work:

sub find_replacement {   ($match, $patterns, $rhash) = @_;   foreach $pattern (@$patterns) {     if ($match =~ s/$pattern/$$rhash{$pattern}/e) {       return $match;     }   }   die "impossible!"; }  @patterns = keys(%rhash); $re = join("|", @patterns);  $str =~ s/$re/find_replacement($&, \@patterns, \%rhash)/ge; 

Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -