# I have already read the 2-column table file into %table. # I've also already opened INFILE and OUTFILE my @keys_ordered = sort { length $table_ref->{$b} <=> length $table_ref->{$a} } keys %{$table_ref}; # Sorted in reverse order of length, so that longer strings # in the data file are found before shorter strings # Done here to increase speed, vs inside the while loop my $replacecount = 0; while ( my $old_line = ) { my $new_line = $old_line; for my $key ( @keys_ordered ) { my $old_count = my $new_count = 0; if ($old_count = ($old_line =~ /\Q$key\E/g)) { $new_count = ( $new_line =~ s/\Q$key\E/$table_ref->{$key}/g ); } if ($new_count != $old_count) { die "Match count failure ($old_count/$new_count) on $line" } $replacecount += $new_count; } print OUTFILE $new_line; } print "Made $replacecount replacements.\n";