in reply to Multiple replacements with the exception of previously made replacements.

Here's with s///, just in case your 'a' and 'b' are generic, and could actually consist of longer strings:
my %replace = ("a" => "b", "b" => "a"); s/(a|b)/$replace{$1}/g;
  • Comment on Re: Multiple replacements with the exception of previously made replacements.
  • Download Code

Replies are listed 'Best First'.
Re^2: Multiple replacements with the exception of previously made replacements.
by jthiel (Initiate) on Aug 17, 2009 at 14:54 UTC
    Hi guys,

    I'm still impressed by how fast you get great replies here, I knew I could count on you.

    rovf and JavaFan:
    Awesome, I wouldn't have been able to think of that solution.

    Originally I was wondering about a way to do it with a single s/// operation but without any helper variable,
    but this is a great way and it allows me to leave the s/// and edit the hash's keys and values the way I like.

    Thanks a lot! :)
      If you want to leave the s/// while be able to add hash elements, write it like this:
      my %replace = (....); my $pat = join '|', map {quotemeta} keys %replace; s/($pat)/$replace{$1}/g;
      Otherwise, you'll have to update the pattern in the s/// if you add a new hash element.
        Hi JavaFan,

        did that now, my statement about leaving the s/// in my previous post wasn't exactly true, yeah.

        That's sweet, so is quotemeta.

        I'm gonna have to mess around with map a little more, the map solution in my initial post was provided by a friend of mine.

        What can I say, thanks a lot, again, greatly appreciating all replies!