Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: 3 Examples of Multiple-Word Search n Replace

by enoch (Chaplain)
on Jun 27, 2003 at 21:20 UTC ( [id://269746]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://269746]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2024-04-24 23:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found