| | |||||||
| |||||||
| |||||||
|
|
|
|
|
|
|
The Transliteration Operator in Perl(Page 1 of 2 ) In this third part of a three-part article series on string processing in Perl, you will learn how to use the transliteration operator. This article is excerpted from chapter nine of the book Beginning Perl, Second Edition, written by James Lee (Apress; ISBN-10: 159059391X). Transliteration Now let’s look at another text processing operator—the transliteration operator. Its syntax is tr/old/new/ This operator resembles the substitute operator,s///, that we saw in Chapter 7 when we discussed regular expressions. While thetr///operator resembless///, the only thing it has in common with the substitute is that both operators operate on$_by default. Thetr///operator has nothing to do with regular expressions. What this operator does is to correlate the characters in its two arguments, one by one, and use these pairings to substitute individual characters in the referenced string. The codetr/one/two/replaces all instances of “o” in the referenced string with “t”, all instances of “n” with “w”, and all instances of “e” with “o”. This operator translates the characters in$_by default. To translate a string other than$_, use the=~ operator as in $string =~ tr/old/new/; Let’s say you wanted to replace, for some reason, all the numbers in a string with letters. You might say something like this: $string =~ tr/0123456789/abcdefghij/; This would turn, say, “2011064” into “cabbage”. You can use ranges in transliteration, but not any of the character classes. We could write the preceding as $string =~ tr/0-9/a-j/; The return value of this operator is, by default, the number of characters transliterated. You can therefore use the transliteration operator to count the number of occurrences of certain characters. For example, to count the number of vowels in a string, you can use my $vowels = $string =~ tr/aeiou//; Note that this will not actually change any of the vowels in the variable$string—as the second group is blank, it is exactly the same as the first group. However, the transliteration operator can take the/dmodifier, which will delete occurrences on the left that do not have a correlating character on the right. So, to get rid of all spaces in a string quickly, you could use this line: $string =~ tr/ //d; Here is an example program that loops through the diamond operator, reading line by line through either the file or files on the command line or standard input. For each line, the tr///operator is used to uppercase the lowercase letters in$_: #!/usr/bin/perl -w while (<>) { Here is an example of executing this program. We invoke it with no command line arguments so it reads though our standard input until end of file (^Din Unix,^Z<enter> $ perl tr.pl More Programming Basics Articles |
| |
| |