Le Fem
Le Fem

Reputation: 109

Why does tr/a-z/b/d replace a in perl?

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

Answers (3)

Barmar
Barmar

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

Henno Brandsma
Henno Brandsma

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

TLP
TLP

Reputation: 67910

The search list is a-z. The replacement list is b. The option /d is given. This means replace a with b, and delete all other matches that have no replacement. Documentation here.

Upvotes: 4

Related Questions