in reply to How to count substitutions on an array
If your substitutions are all literal substitutions, i.e., all of the form
'banana' => 'plum'
'xyzzy' => 'whatever'
and never of the form
/f[eio]e+/ => 'something'
and definitely not the sort of thing BillKSmith is doing here, then the following approach might be helpful. If you have many substitutions to make, the alternation of the $search regex may grow quite large, but with the alternation trie optimization of Perl version 5.10, this should not be a problem — unless it gets really big! (My guess is that 10K search-replace pairs could be handled.)
Of course, you would go through your @substitutionlist array to build the %direct_substitution hash before processing the @lines array.c:\@Work\Perl>perl -le "use 5.010; ;; use warnings; use strict; ;; my %direct_substitution = ( 'apple' => 'PEAR', 'red' => 'YELLOW', 'xyzzy' => 'SOME OTHER THING', ); ;; my ($search) = map qr{ \b (?: $_ ) \b }xms, join q{ | }, keys %direct_substitution ; print $search; ;; my @lines = ( 'apple xapple apple applex xapplex apple', 'red', 'xxx red apple yyyy xyzzy zz', ); ;; my $count = 0; $count += s{ ($search) }{$direct_substitution{$1}}xmsg for @lines; ;; print qq{substitutions: $count}; print qq{'$_'} for @lines; " (?^msx: \b (?: apple | red | xyzzy ) \b ) substitutions: 7 'PEAR xapple PEAR applex xapplex PEAR' 'YELLOW' 'xxx YELLOW PEAR yyyy SOME OTHER THING zz'
Give a man a fish: <%-{-{-{-<
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to count substitutions on an array
by Anonymous Monk on Aug 13, 2016 at 19:35 UTC | |
by AnomalousMonk (Archbishop) on Aug 14, 2016 at 00:51 UTC |