O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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/; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required