Jemts has asked for the wisdom of the Perl Monks concerning the following question:

Is there any practical difference between tr/pattern/replacment/ and s/pattern/replacment/g


"If you're traveling in a time machine, and you're eating corn on the cob, I don't think it's going to affect things one way or the other. But here's the point I'm trying to make: Corn on the cob is good, isn't it."
  • Comment on Question about use of tr/ / / and s/ / /g

Replies are listed 'Best First'.
(jeffa) Re: Question about use of tr/ / / and s/ / /g
by jeffa (Bishop) on May 06, 2001 at 19:18 UTC
    Yes. The terse explanation can be perused at perlop, but here is simple explanation in the meantime:

    tr/// is the transliteration operator. It is used to convert all occurances of one character class to another:

    s/// is the substitution operator. It replaces a pattern with some replacement string:
    The differences in the results can be subtle. A great explanation of when to use to which (don't rule out substr as a solution either) can be found at Code Smarter.


Re: Question about use of tr/ / / and s/ / /g
by merlyn (Sage) on May 06, 2001 at 19:33 UTC
    If it's a single character to other single character, or single character to empty mapping, without regard to surrounding character context, tr/// will certainly beat s///, as it's the simpler operator to do so.

    So, use tr/// if it can do the job, otherwise use s///.

    -- Randal L. Schwartz, Perl hacker

Re: Question about use of tr/ / / and s/ / /g
by virtualsue (Vicar) on May 06, 2001 at 19:19 UTC
    Yes indeed - mainly because tr/// doesn't understand regular expressions.
Re: Question about use of tr/ / / and s/ / /g
by mincus (Chaplain) on May 06, 2001 at 19:20 UTC
    tr/// does transliteration... it maps characters to other characters.

    s/// will take a pattern and replace the pattern...

    This will explain it in much more detail...

    Best of luck!

    Listen to jeffa, he makes much more sence than I... but the best way to understand the difference is still Here