The tr/// Operator (Transliteration)
tr/SEARCHLIST/REPLACEMENTLIST/cdsr LVALUE =~ tr/SEARCHLIST/REPLACEMENTLIST/cds RVALUE =~ tr/SEARCHLIST/REPLACEMENTLIST/cdsr RVALUE =~ tr/SEARCHLIST//c
For sed devotees, y/// is provided as a synonym for tr///. This is why you can’t call a function
named y, any more than you can call a
function named q or m. In all other respects, y/// is identical to tr///, and we won’t mention it again.
This operator might not appear to fit into a chapter on pattern
matching since it doesn’t use patterns. This operator scans a string,
character by character, and replaces each occurrence of a character
found in SEARCHLIST (which is not a regular
expression) with the corresponding character from
REPLACEMENTLIST (which is not a replacement
string). It looks a bit like m// and
s///, though, and you can even use
the =~ or !~ binding operators on it, so we describe it
here. (qr// and split are pattern-matching operators, but you
don’t use the binding operators on them, so they’re elsewhere in the
book. Go figure.)
Transliteration returns the number of characters replaced or
deleted. If no string is specified via the =~ or !~
operator, the $_ string is altered.
The SEARCHLIST and
REPLACEMENTLIST may define ranges of
sequential characters with a dash:
$message =~ tr/A–Za–z/N–ZA–Mn–za–m/; # rot13 encryption.
Note that a range like A–Z assumes a linear character set like ASCII. But each character set has its own ideas of how characters are ordered and thus of which characters ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access