Jump to content

Here is an example of the tr, or transliteration, operator


G+_Joe Maruschek
 Share

Recommended Posts

Here is an example of the tr, or transliteration, operator.

 

I was curious about this TR operator that Padre mentioned on the show.  This is what I learned.

 

Sometimes you might have a need to replace every letter "a" with the letter "b", and every letter "b" with the letter "a".  You can try to do that using the s/// operator to do two substitutions, but the second substitution will undo the first one.  The TR operator can do such a translation like this:

 

$var =~ tr/ab/ba/

 

The TR operator works character-by-character.  It looks through the $var and takes characters after the first slash and replaces them with the corresponding character after the second slash.  I doesn't work on words, just characters.  It doesn't even use regular expressions at all, just a set of "before" characters" and a set of "after" characters.  For example, you can replace the letter "a" with the number "1", the letter "b" with the number "2", and the letter "c" with the number "3" with this statement:

 

$var =~ tr/abc/123/

 

You can use a dash to indicate a range of characters.  If you want to make all lowercase letters uppercase, you can do this:

 

$var =~ tr/a-z/A-Z/

 

The example code uses the TR operator to encode a message using a scheme that the old folks will recognize as ROT13.  Go ahead and play with the code and see what other uses you can find for the TR operator.

https://github.com/joemarus/perl_examples/blob/master/encode_decode.pl

Link to comment
Share on other sites

Handy little feature when you need it. I once wrote an interface where I created and then uploaded a file to another company. The file was a normal ASCII text file except, for reasons unknown, the floating-point values needed to be coded in EBCDIC. Fortunately I had found a library of powerful string functions for Delphi that had a Translate function that does just what Perl's TR does that I was able to use on the floating-point fields.

Link to comment
Share on other sites

 Share

×
×
  • Create New...