Reputation: 109
Why does tr/a-z/b/d
replace character a
in perl? Isn't it meant to delete all characters from a to z
?
$string = 'the cat sat on the mat.';
$string =~ tr/a-z/b/d;
print "$string\n"; # => b b b. Why?
Upvotes: 1
Views: 766
Reputation: 781834
From the documentation:
If the
/d
modifier is used, the REPLACEMENTLIST is always interpreted exactly as specified. Otherwise, if the REPLACEMENTLIST is shorter than the SEARCHLIST, the final character is replicated till it is long enough.
Since you used the /d
modifier, REPLACEMENTLIST
is not extended. So a
is replaced with b
, and the rest of the letters matched by a-z
are deleted because there's nothing in REPLACEMENTLIST
to replace them with.
If you do it without the /d
modifier, you'll get your expected behavior. It will be equivalent to:
tr/a-z/bbbbbbbbbbbbbbbbbbbbbbbbbb/
because of the replication.
Upvotes: 5
Reputation: 2166
The second range is shorter than the first. So a gets replaced by b, and b-z get replaced by the empty string because of the extra d flag at the end.
Upvotes: 3