15.5. 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 already do that 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 the first one made.

From the UNIX shell, however, such a data transformation is simple: just use the standard tr (1) command:

tr ab ba <indata >outdata

(If you don't know anything about the tr command, please look at the tr (1) manpage; it's a useful tool for your bag of tricks.) Similarly, Perl provides a tr operator that works in much the same way:

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 arguments to the tr operator are similar to the arguments to the tr (1) command. 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/; ...

Get Learning Perl, Second Edition 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.