wHellow fellow monks.
A friend asked me recently if it is possible in Perl to simulate this code from php:
$bad_words = array('ugly', 'anotherugly'); $good_words = array('ug**','anot******y'); $txt = 'ugly anotherugly'; $txt str_replace($bad_words, $good_words, $txt);
In this code he first creates a list of bad_words that he want's to search for, then creates a list of good_words to subsitute instead of the found bad ones. He gives the str_replace the bad and good words only telling him on what string it should work on.
I came up with this solution:
#!/usr/bin/perl use warnings; use strict; my %words = ( ugly => 'ug**', anotherugly => 'anot*******', ); my $txt = "ugly anotherugly"; $txt =~ s/$_/$words{$_}/g foreach %words; print $txt;
It works fine, but I am wondering about a few things, that are beyond my kwnoledge.
1. Is it the most efficient way?
2. How is it done by php's str_replace, does it iterate over each bad word as my foreach loop iterates over %words?
3. Is it at least that fast as the use of php's str_replace?
4. Is there a better way to do it?

I am almost sure that it can be done much better ( more efficient ) in Perl than I did. I tried to search the perldoc but with no luck. Maybe some of you fellow Monks had expirience with such construct's ( maybe those that work with CGI ? ) and have a relatively good equivalent for the php code.
I await your replies, and hope to see some interesting solutions, or just simple ideas how to solve this problem?

In reply to Substitute 'bad words' with 'good words' according to lists by mulander

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.