The Translation Operator in Perl


Translation is similar, but not identical, to the principles of substitution in Perl, but unlike substitution, translation (or transliteration) does not use regular expressions for its search on replacement values. The translation operators are −

tr/SEARCHLIST/REPLACEMENTLIST/cds
y/SEARCHLIST/REPLACEMENTLIST/cds

The translation replaces all occurrences of the characters in SEARCHLIST with the corresponding characters in REPLACEMENTLIST. For example, using the "The cat sat on the mat." string we have been using in this chapter −

Example

 Live Demo

#/user/bin/perl
$string = 'The cat sat on the mat';
$string =~ tr/a/o/;
print "$string\n";

When above program is executed, it produces the following result −

The cot sot on the mot.

Standard Perl ranges can also be used, allowing you to specify ranges of characters either by letter or numerical value. To change the case of the string, you might use the following syntax in place of the uc function.

$string =~ tr/a-z/A-Z/;

Translation Operator Modifiers

Following is the list of operators related to translation.

Sr.NoModifier & Description
1c
Complements SEARCHLIST.
2d
Deletes found but unreplaced characters.
3s
Squashes duplicate replaced characters.

The /d modifier deletes the characters matching SEARCHLIST that do not have a corresponding entry in REPLACEMENTLIST. For example −

Example

 Live Demo

#!/usr/bin/perl
$string = 'the cat sat on the mat.';
$string =~ tr/a-z/b/d;
print "$string\n";

When above program is executed, it produces the following result −

b b b.

The last modifier, /s, removes the duplicate sequences of characters that were replaced, so −

Example

 Live Demo

#!/usr/bin/perl
$string = 'food';
$string = 'food';
$string =~ tr/a-z/a-z/s;
print "$string\n";

When above program is executed, it produces the following result −

fod

Updated on: 29-Nov-2019

488 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements