next up previous contents
Next: The Translation Options Up: Regular Expressions Previous: The Matching Options

The Translation Operator (tr///)

The translation operator (tr///) is used to change individual characters in the $_ variable. It requires two operands, like this:

tr/a/z/;

This statement translates all occurrences of a into z. If you specify more than one character in the match character list, you can translate multiple characters at a time.

For instance:

tr/ab/z/;

translates all a and all b characters into the z character. If the replacement list of characters is shorter than the target list of characters, the last character in the replacement list is repeated as often as needed. However, if more than one replacement character is given for a matched character, only the first is used. For instance:

tr/WWW/ABC/;

results in all W characters being converted to an A character. The rest of the replacement list is ignored.

Unlike the matching and substitution operators, the translation operator doesn't perform variable interpolation.

Note The tr operator gets its name from the UNIX tr utility. If you are familiar with the tr utility, then you already know how to use the tr operator. The UNIX sed utility uses a y to indicate translations. To make learning Perl easier for sed users, y is supported as a synonym for tr.



 
next up previous contents
Next: The Translation Options Up: Regular Expressions Previous: The Matching Options
dave@cs.cf.ac.uk