in reply to Match first word in line fails
#!/usr/bin/perl -w use strict; my %bad_words = ( 'crud' => 'dirt', 'crap' => 'dung', 'poo' => 'dung', 'wanker' => 'fool' ); my $bad_re = join '|', keys %bad_words; while ( <DATA> ) { s/\b($bad_re)\b/$bad_words{lc($1)}/ieg; print; } __DATA__ "Wanker!" said I. "Crap," says Travis. This is horse poo. Poo, I tell you! "Poo upon all the crud and crap the wanker could see."
When I tested this, it did what I think is being sought. Other than the building of the wordlist hash and the displaying (or writing to file, or assigning to a variable) of the changed text, it's just one line outside the loop to get ready for the regex, and one inside the loop to do the work. Here's my output:
"fool!" said I. "dung," says Travis. This is horse dung. dung, I tell you! "dung upon all the dirt and dung the fool could see."
There's no need, as far as I can tell, for anything besides search and replace when what's wanted is search and replace.
Update: Looking back at this, the /e on the s/// isn't necessary.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Match first word in line fails
by ysth (Canon) on Jan 30, 2005 at 10:36 UTC | |
by mr_mischief (Monsignor) on Jan 31, 2005 at 06:33 UTC | |
by ysth (Canon) on Feb 02, 2005 at 06:52 UTC |