11. Transliteration

The transliteration operator (also called translation operator) works like the substitution regular expression but it does not use regular expressions and works differently. The syntax is as follows:

tr/search/replacement/

tr has useful applications (BTW tr can be replaced by a synonym: y). Study the next examples.
11.1 tr and $_
tr operates on the special variable $_ (if no other variable is defined).
$_ = "da, da, da!";
tr/a/X/;
print $_ . "\n"; # output: dX, dX, dX!
$_ = "UPPERCASE!";
tr/[A-Z]/[a-z]/;
print($_ . "\n"); # output: uppercase!
$_ = "aaabbbccc";
tr/[a-c]/bgh/;
print($_ . "\n)"; # output: bbbggghhh
$_ = "+++***"
$c = tr/+*/-#/;
print($c, ": ", $_ , "\n"); # output: 6: ---###
11.2 tr and =~
Use the binding operator =~ if you want to use tr on a variable:
$str = "aaabbbccc";
$str =~ tr/[a-c]/bgh/;
print($str . "\n"); # output: bbbggghhh
$str = "aaabbbccc";
$str =~ tr/[a-c]/[1-3]/;
print($str . "\n"); # output: 111222333
$str = "aaabbbccc";
$str =~ tr/[ac]/1/; # equals tr/ac/11/
print($str . "\n"); # output: 111bbb111
11.3 A counting trick
$_ = "a1b2c6";
$no = tr/0-9//;
print($no . "\n"); # output: 3 (count the number of digits)
$str= "this is what it is";
$no = $str =~ tr/i//;
print($no . "\n"); # output: 4 (count the number of occurrences of character i)
Counting and replacing (no suprise):
$str= "this is what it is";
$no = $str =~ tr/i/E/;
print("$no $str"\n"); # output: 4 thEs Es what Et Es
11.4 Modifiers 'c', 'd' and 's'
$_= "1234abc7890";
tr/0-9//d;
print($_ . "\n"); # output: abc (with option 'd' from 'delete')
$_= "00    001      112      22";
tr/ //d;
print($_ . "\n"); # output: 0000111222 (with option 'd' from 'delete')
$_= "1234abc7890";
tr/0-9/ /c;
print($_ . "\n"); # output: 1234 7890 (with option 'c' from 'complement', here complement of numbers 0-9, i.e. NOT a number, will be replaced by space)
The third modifier 's' (from squeeze) removes duplicate characters:
$_= "000011122233444445566778899";
tr/0-9//s;
print($_ . "\n"); # output: 0123456789 (with option 's' from 'squeeze')
11.5 A simple letter substitution cipher: ROT13

sub rot13 {
    $text = shift;
    $text =~ tr/A-Za-z/N-ZA-Mn-za-m/;
    return $text;
}

$input = "Hello, World!";
$output = rot13($input);

print("Original: $input\n");
print("ROT13   : $output\n"); # output: Uryyb, Jbeyq!    
This Perl code defines a rot13 subroutine ('rotate by 13 places') that takes a string as input and applies ROT13 using the tr function. The tr function is used to transliterate characters in the input string according to the specified mapping. In this case, it maps each letter to the letter 13 positions ahead in the alphabet.

Note that this implementation only applies ROT13 to alphabetic characters, leaving non-alphabetic characters unchanged.