perl function tr

The tr function in Perl is used for character translation or transliteration. It takes two sets of characters and replaces the characters in the first set with corresponding characters in the second set. The syntax of the tr function is:

refe‮:ot r‬theitroad.com
tr/SEARCHLIST/REPLACEMENTLIST/cdsr

Here,

  • SEARCHLIST is the set of characters to be searched for
  • REPLACEMENTLIST is the set of characters that will replace the searched characters
  • c, d, s, and r are optional modifiers. c stands for complement, d stands for delete, s stands for squeeze, and r stands for return.

Here is an example that shows how the tr function works:

my $string = "hello world";
$string =~ tr/ol/OL/;  # replaces all "o" and "l" with "O" and "L"
print $string;  # Output: heLLO wOrLd

In this example, the tr function replaces all "o" and "l" characters in the $string variable with "O" and "L" respectively. The output is "heLLo wOrLd".