in reply to multi find/replace

Anonymous Monk,
Assuming you do not care about performance and are only looking to reduce 20 lines of code down to 1, you could do the following:
$string =~ s/$_/$table{$_}/g for keys %table;
Where the key in %table is the thing to replace and the value is what to replace it with.

Cheers - L~R

Update: It looks like Enlil and I had about the same idea. The difference is his regex only runs once while mine runs as many times as there are keys in hash. I know that alternation really slows down a regex, but his method is still probably faster overall though you could benchmark it if you wanted to know for sure.

Replies are listed 'Best First'.
Re: Re: multi find/replace
by bart (Canon) on Feb 10, 2004 at 21:52 UTC
    Going through it all just once has more benefits than just speed. Imagine for example, that you have to replace every occurrence of "A" with "B", of "B" with "C", and of "C" with "A" — thus swapping places. That's extremely easy if you do it in one go, and quite impossible to do it in three iterative substitutions.

    Good:

    %replace = ( A => 'B', B => 'C', C => 'A'); s/(A|B|C)/$replace{$1}/g;

    Bad:

    s/A/B/; s/B/C/; s/C/A/;
    For the latter, everything that was "A", "B" or "C", will now be "A".
      bart,
      While you have a valid point, it is not applicable to this problem. The code you state as bad is what the AM already stated as working. While I do not promote my solution as the best one to use, it certainly does save keystrokes.

      Cheers - L~R