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

The difference was confusing for me, as well, when I first started learning Perl. The discussion of speed, notwithstanding, it should be noted that tr// isn't as 'flexible' as s// because the former will only translate the exact number of characters in the original string as there are characters in the replacement list. So, beyond our replacement of '+' signs:
$toto = 'this+is+my+text'; $toto =~ tr/my/your/d;
$toto will now equal 'this+is+yo+text'. Where:
$toto = 'this+is+my+text'; $toto =~ s/my/your/;
$toto will now equal 'this+is+your+text'. A helpful distinction that is not blatantly obvious in the reading of Perl docs.

—Brad
"A little yeast leavens the whole dough."

Replies are listed 'Best First'.
Re: Re: Difference between tr// and s///?
by CountZero (Bishop) on Feb 06, 2004 at 17:10 UTC
    Also do not forget that tr/// has no concept of "words". So if you do a tr/this/that/, it means that all 't' get replaced by 't'; 'h' by 'h', 'i' by 'a' and 's' by 't', which is probably not what you wanted if you expected all words "this" to be replaced by the word "that" (which of course will happen, but at the same time "is" will be changed into "at"). So tr/// will work on individual characters only. If you need to do some more sophisticated work, use s///.

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law