in reply to Difference between tr/// and s///?

They are not equivalent. $toto =~ s/\+//g; removes all plus signs. $toto =~ tr/+// only counts the plus signs. If you want to delete them, use tr/+//d. But the latter is still prefered over s/\+//g for performance reasons. tr is faster. Of course, in many practical cases, the speed difference is too small to notice.

Abigail

Replies are listed 'Best First'.
Re: Re: Difference between tr// and s///?
by calin (Deacon) on Feb 06, 2004 at 10:35 UTC
    Notice there's a space between the second and third slash in the OP's code example. With proper code tags you can see more clearly:

    $toto = 'this+is+my+text'; $toto =~tr/+/ /; why not $toto =~s/\+/ /g; ?
      Ah, yes, I didn't realize that originally the OP didn't use <code> tags, so I didn't notice the space.

      My second point still stands though, tr/// is usually faster than s///. It is faster because tr/// is a much simpler operation. It's a character by character replacement - no copy of the string needs to be made, nor do large parts of the string be moved. An s/// operation cannot assume such a thing, replacement parts can be shorter or smaller than the thing that needs to be replaced.

      Abigail