[Solved] Fast multiple search and replace in Perl


Use a hash. Use the old strings as keys, replacement strings as values.

#!/usr/bin/perl
use warnings;
use strict;

my %map;
open my $MAP, '<', 'map.txt' or die $!;
while (<$MAP>) {
    my ($pattern, $replacement) = /(.*) { (.*) };/;
    $map{$pattern} = $replacement;
}

open my $IN, '<', 'input.txt' or die $!;
while (<$IN>) {
    s/"(.*)"https://stackoverflow.com/"$map{$1}"/g;
    print;
}

To output to a new file, change the last paragraph as follows:

open my $IN,  '<', 'input.txt' or die $!;
open my $OUT, '>', 'output.txt' or die $!;
while (<$IN>) {
        s/"(.*?)"/exists $map{$1} ? qq{"$map{$1}"} : qq{"$1"}/ge;
    print {$OUT} $_;
}
close $OUT;

10

solved Fast multiple search and replace in Perl