$_ = "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: ---###
$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
$_ = "a1b2c6";
$no = tr/0-9//;
print($no . "\n");# output: 3 (count the number of digits)
Counting and replacing (no suprise):$str= "this is what it is";
$no = $str =~ tr/i//;
print($no . "\n");# output: 4 (count the number of occurrences of character i)
$str= "this is what it is";
$no = $str =~ tr/i/E/;
print("$no $str"\n");# output: 4 thEs Es what Et Es
$_= "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')
The third modifier 's' (from squeeze) removes duplicate characters:$_= "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)
$_= "000011122233444445566778899";
tr/0-9//s;
print($_ . "\n");# output: 0123456789 (with option 's' from 'squeeze')
This Perl code defines a rot13 subroutine ('rotate by 13 places') that takes a string as input and applies ROT13 using thesub 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!