perl - How to replace a set of search/replace pairs? -


i have dictionary of translations hash:

my %dict = { hello => 'hola', goodbye => 'adios' , ... } 

(the actual use-case not human language translation! i'm replacing load of tokens other values. example.)

how can apply each of these string? loop them , pass each s/$key/$value/ i'd have quote them wouldn't break if search or replacement had (for example) / in it.

in php there's strtr($subject, $replacement_pairs_array) - there similar in perl?

first, hash initialization off: hash initialized list:

my %dict = ( hello => 'hola', goodbye => 'adios' , ... ); 

or can use hash reference:

my $dict = { hello => 'hola', goodbye => 'adios' , ... }; 

which scalar.

replacing keys values in string easy:

s/$_/$dict{$_}/g keys %dict; 

unless

  • the contents of substitutions shall not replaced, e.g. %dict = (a => b, b => c) should transform "ab" "bc" (not "cc" above solution may or may not do, hash order random).
  • the keys can contain regex metacharacters ., +, or (). can circumvented escaping regex metacharacters quotemeta function.

the traditional approach build regex matches keys:

my $keys_regex = join '|', map quotemeta, keys %dict; 

then:

$string =~ s/($keys_regex)/$dict{$1}/g; 

which solves these issues.

in regex building code, first escape keys map quotemeta, , join strings | build regex matches keys. resulting regex quite efficient.

this guarantees each part of string translated once.


Comments