Perl 5.14 adds non-destructive transliteration

[This is a mid-week bonus item since it’s so short]

In Perl 5.13.2, you got a non-destructive version of the substitution operator (Use the /r substitution flag to work on a copy). Instead of changing it’s target, the non-destructive version returns a new string that has the substitution.

Perl 5.13.7 extends the /r to work with transliteration too. You’ll need to Compile a development version of perl to try this example:

use 5.013007;

my $string = 'The quick brown fox youtubed the lazy dog';
my $rot13 = $string =~ tr/a-zA-Z/n-za-mN-ZA-M/r;

print <<"HERE";
PLAIN: $string
CRYPT: $rot13

The output shows you that the original string is the same:

PLAIN: The quick brown fox youtubed the lazy dog
CRYPT: Gur dhvpx oebja sbk lbhghorq gur ynml qbt

The same code (without the /r) with earlier versions of Perl get a completely different result:

my $string = 'The quick brown fox youtubed the lazy dog';
my $rot13 = $string =~ tr/a-zA-Z/n-za-mN-ZA-M/;

print <<"HERE";
PLAIN: $string
CRYPT: $rot13

Instead of the crypt text, you get the count of the number of characters that the transliteration replaced:

PLAIN: Gur dhvpx oebja sbk lbhghorq gur ynml qbt

To get the same effect with older Perls, you have to use the assign-then-modify idiom so the transliteration actually binds to the new version instead of the old version:

# /r for older Perls
( my $rot13 = $string ) =~ tr/a-zA-Z/n-za-mN-ZA-M/;

Random notes

The y/// is just another way to write the transliteration operator (or maybe tr/// is another way to write y/// if you're coming from sed). You find them in perlop under "Quote Like Operators".

Some people confuse transliteration with regular expression matching because the syntax looks similar and Programming Perl discusses transliteration in its "Pattern Matching" chapter. However, the transliteration doesn't use regular expressions. It does a one-to-one replacement of characters on the lefthand side with the corresponding character on the righthand side.

Leave a comment


Leave a Reply

[ Ctrl + Enter ]