Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: 3 Examples of Multiple-Word Search n Replace

by enoch (Chaplain)
on Jun 27, 2003 at 21:20 UTC ( #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


Comment on Re: 3 Examples of Multiple-Word Search n Replace
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (15)
As of 2014-08-27 18:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (250 votes), past polls