G+_Joe Maruschek Posted July 13, 2014 Share Posted July 13, 2014 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 More sharing options...
G+_Darryl Medley Posted July 14, 2014 Share Posted July 14, 2014 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 More sharing options...
G+_Nestor C Posted July 14, 2014 Share Posted July 14, 2014 "Press Enter to close window" worked on Windows 8.1 Interesting example of the transliteration. Link to comment Share on other sites More sharing options...
G+_Shannon Morse Posted July 17, 2014 Share Posted July 17, 2014 Oh wow! This was a great explanation, thank you! Link to comment Share on other sites More sharing options...
G+_L I Posted July 20, 2014 Share Posted July 20, 2014 Love ROT13! Link to comment Share on other sites More sharing options...
Recommended Posts