I have a file and a list of string pairs which I get from another file. I need substitute the first string of the pair with the second one, and do this for each pair.
Is there more efficient/simple way to do this (using Perl, grep, sed or other), then running a separate regexp substitution for each pair of values?
I have a file and a list of string pairs which I get from
Share
The
@{[...]}bit may look strange. It’s a hack to interpolate generated content inside quote and quote-like operators. The result of thejoingoes inside the anonymous array-reference constructor[]and is immediately dereferenced thanks to@{}.If all that seems too wonkish, it’s the same as
minus the temporary variable.
Note the use of
quotemeta—thanks Ivan!—which escapes the first string of each pair so the regular-expression engine will treat them as literal strings.Output:
Metaprogramming—that is, writing a program that writes another program—is also nice. The beginning looks familiar:
Now we generate the program that does all the
s///replacements—but isquotemetaon the replacement side a good idea?—and compile it with
eval:To do the replacements, we use Perl’s ready-made in-place editing:
Below is an extra nicety that restores backups that the File::Compare module judges to have been unnecessary: