http://qs321.pair.com?node_id=269746


in reply to 3 Examples of Multiple-Word Search n Replace

In the spirit of laziness as it pertains to maintaining/adding-things-to code, I would rewrite the first example to automatically generate the words to be replaced from the keys in the hash (and, I was just a little bored, so I did this).
my %ch = ('green' => 'lousy', 'blue' => 'cool', 'pink' => 'mini',) ; my $str = 'I have a green hat, blue shirt, plus a pink jacket'; print $str . "\n" ; my $keyList = '('. (join '|', keys %ch) . ')'; my $regex = qr/$keyList/; $str =~ s/$regex/$ch{$1}/g; print $str ;
That way, if we wanted to change all instances of 'hat' to 'fedora', we just add it to the hash and go about our business.
my %ch = ('green' => 'lousy', 'blue' => 'cool', 'pink' => 'mini', 'hat' => 'fedora') ; my $str = 'I have a green hat, blue shirt, plus a pink jacket'; print $str . "\n" ; my $keyList = '('. (join '|', keys %ch) . ')'; my $regex = qr/$keyList/; $str =~ s/$regex/$ch{$1}/g; print $str ; __END__ I have a green hat, blue shirt, plus a pink jacket I have a lousy fedora, cool shirt, plus a mini jacket
TIMTOWTDI,
enoch