Reputation: 75
I got got such line:
print "a b c" =~ tr/a-z/c-za-b/r . "\n";
Which basically translates a b c
to c d e
,but I don't completely understand is how this works.
So, lets have a look at this part:
tr/a-z/c-za-b/r
tr
is used in perl for transliterating, which is clear and ok for me.
in the part /a-z/
part we select all lowercase letters from a to z, the second part /c-za-b/
is mystery to me, I tried to experiment but can't figure out how this works. Can someone explain how this being converted or link me to some good explanation or manual ?
Thanks
Upvotes: 1
Views: 514
Reputation: 904
You're not alone in finding it incomprehensible. tr// is rarely used in modern code.
Anyway, in Perl-speak, if you have a line like:
$x=~tr/0-9a-f/a-p/;
That is roughly:
my @in = (0 .. 9, "a" .. "f");
my @out = ("a" .. "p");
for my $i (0 .. $#in) {
$x =~ s/$in[$i]/$out[$i]/g;
}
It's a little more complicated than that because tr//
doesn't work iteratively, but this should give you a good sense of what's going on.
Upvotes: 1
Reputation: 118665
a-z
is expanded to the 26 character string abcdefghijklmnopqrstuvwxyz
.
c-za-b
is expanded to the 26 character string cdefghijklmnopqrstuvwxyzab
.
Given the two strings
1. abcdefghijklmnopqrstuvwxyz
2. cdefghijklmnopqrstuvwxyzab
$string =~ tr/a-z/c-za-b/
converts each character it can find in the first row into the corresponding character in the second row.
Similar notation is used to implement the reversible rot13 encoding:
($encoded = $original) =~ tr/a-zA-Z/n-za-mN-ZA-M/;
($encoded2 = $encoded) =~ tr/a-zA-Z/n-za-mN-ZA-M/; # now $encoded2 eq $original
Upvotes: 8