$replacecount += ( $line =~ s/\Q$key\E/$table_ref->{$key}/g );
to avoid unintended consequences. It's probably a good idea any, just in case. See String interpolation to see a bit more about how interpolation works in Perl.
Regarding the main part of your question, I read your issue as "I want all substitutions to only occur if they would have occurred on the original file". Might I suggest, then caching the original line and testing if you would have a match before substituting? You could put an error statement in there as well to make sure the number of substitutions matched the number of expected substitutions. Something like:
# 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 = <INFILE> ) { 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";
In reply to Re: Algorithm to search and replace on data file, based on a table file?
by kennethk
in thread Algorithm to search and replace on data file, based on a table file?
by koknat
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |