y///#
Transliterate characters in a string. y/// is a synonym for
tr/// — the two are identical in every respect.
The y spelling is provided for sed devotees, whose muscle memory
produces y/abc/ABC/ rather than tr/abc/ABC/. Perl’s parser accepts
either; the resulting op is the same. Use whichever spelling reads
better in the surrounding code — if the file already quotes a sed
script, y/// often fits; in fresh Perl, tr/// is more common.
Synopsis#
y/SEARCHLIST/REPLACEMENTLIST/cdsr
$var =~ y/SEARCHLIST/REPLACEMENTLIST/cdsr
y/SEARCHLIST/REPLACEMENTLIST/ # transliterates $_
What you get back#
Same as tr///:
Without
/r: the number of characters matched (and replaced or deleted), after modifying the target in place.With
/r: a new string with the transliteration applied; the original is untouched.
Examples#
Classic sed-style uppercase transliteration on $_:
while (<>) {
y/a-z/A-Z/;
print;
}
Counting vowels without modifying the string, using /r to discard
the transliterated copy:
my $vowels = ($text =~ y/aeiouAEIOU//) ; # count in place is fine too
my $count = () = $text =~ /[aeiouAEIOU]/g;
Strip everything except digits from a string (non-destructive copy
via /r, complement + delete):
my $digits = $phone =~ y/0-9//cdr; # "(415) 555-1212" → "4155551212"
Rot13 — the textbook y/// one-liner:
(my $coded = $plain) =~ y/A-Za-z/N-ZA-Mn-za-m/;
Edge cases#
See tr/// for the full list. Two worth repeating here:
No variable interpolation.
y/$x/$y/transliterates the literal characters$,xagainst$,y— not the contents of those variables. This matchestr///and is the single most common sed-to-Perl translation bug.y'...'...'disables ranges. With single-quote delimiters,-is literal:y'a-z'A-Z'transliterates onlya,-,zagainstA,-,Z.
Differences from upstream#
Fully compatible with upstream Perl 5.42.
See also#
tr///— the canonical spelling; identical semantics, same flags (/c,/d,/s,/r), same edge casess///— pattern-based substitution when character-by-character mapping is not enoughlc,uc— locale- and Unicode-aware case change; prefer these overy/a-z/A-Z/for anything beyond ASCII$_— the default target when no=~binding is given