in reply to Turn Hate Mail to Love Letter: Regex Multi-Word/Phase Replace

how about:
: : $profane{qr/piss (us|you) off/i} = 'lift $1 off'; : : : : $text =~ s/($profanity)/eval '"'.$profane{$1}.'"'/ge; : :
as a first try? Won't work with quotes in the replacement, but that's an easy one ;-)

Replies are listed 'Best First'.
Re: Re: Turn Hate Mail to Love Letter: Regex Multi-Word/Phase Replace
by chunlou (Curate) on Jun 25, 2003 at 12:21 UTC
    Good trick. But when s/($profanity)/eval '"'.$profane{$1}.'"'/ge turns to s/($profanity)/lift $1 off/g, doesn't it give you "life piss you off off" since "piss you off" is what being captured into $1?

    Consider this:
    $_ = "candies lift me up"; s/(cand(y|ies)|lift(s|) (me|us) up)/1 $1; 2 $2; 3 $3; 4 $4;\n/g; print ; __END__ 1 candies; 2 ies; 3 ; 4 ; 1 lift me up; 2 ; 3 ; 4 me;
    "me" is captured in $4. In other words, we don't know ahead of time which of the $1 .. $n "me" will end up in when the regex can have arbitrary many brackets.
      Good point regarding my example.

      I should have used $2 instead. But I don't think this is a problem. You just have to remember to add 1 to your $n.

      Otherwise you could go the $&-way:

      s/$profanity/eval '"'.$profane{$&}.'"'/ge;
        $& is unnecessary. $1 is fine.

        The $n in the key, say, 'lift $n up', is not static in a sense that if someone adds a new key/value pair, the $n will have to be changed. And it's not incremental by 1. It depends on how many bracketing constructs in total in the search pattern.

        But your answer is in the right direction I think.

        Thanks.