Transliteration

When you want to take a string and replace every instance of some character with some new character, or delete every instance of some character, you can do so with carefully selected s/// commands. But suppose you had to change all of the a’s into b’s, and all of the b’s into a’s? You can’t do that with two s/// commands because the second one would undo all of the changes that the first one made.

Perl provides a tr operator that does the trick:

tr/ab/ba/;

The tr operator takes two arguments: an old string and a new string. These arguments work like the two arguments to s///; in other words, there’s some delimiter that appears immediately after the tr keyword that separates and terminates the two arguments (in this case, a slash, but nearly any character will do).

The tr operator modifies the contents of the $_ variable (just like s///), looking for characters of the old string within the $_ variable. All such characters found are replaced with the corresponding characters in the new string. Here are some examples:

$_ = "fred and barney";
tr/fb/bf/;        # $_ is now "bred and farney"
tr/abcde/ABCDE/;  # $_ is now "BrED AnD fArnEy"
tr/a-z/A-Z/;      # $_ is now "BRED AND FARNEY"

Notice how a range of characters can be indicated by two characters separated by a dash. If you need a literal dash in either string, precede it with a backslash.

If the new string is shorter than the old string, the last character of the new string is repeated enough times to make the strings equal length, ...

Get Learning Perl on Win32 Systems now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.