Can somebody explain the tr /d modifier in perl? [duplicate]
Asked Answered
B

1

6

I found this example in a Perl tutorial, but could not understand the output. The tutorial says:

The /d modifier deletes the characters matching SEARCHLIST that do not have a corresponding entry in REPLACEMENTLIST.

but I could not figure out how this is realized in the example.

Can somebody explain how the output was generated?

Script:

$string = 'the cat sat on the mat.';
$string =~ tr/a-z/b/d;
print "[$string]\n";

Output:

[ b b   b.]

(The square brackets mark the start and end of the string, that's all.)

Betimes answered 22/8, 2015 at 22:7 Comment(2)
That's a transliteration, it has nothing to do with regex ;)Ataliah
How odd - the duplicate question uses the very same example text.Facetious
F
10

Since there is only one character in the replacement list (b), only the first character in the searchlist (a) will be replaced with b. The rest of characters in the search list (b-z) will be deleted.

Hence, replacing as with bs and b-z letters with nothing,

the cat sat on the mat.

becomes  b b   b. (there are only three as in the sentence and the spaces and the dot are preserved as they were not part of the searchlist).

Fluorescein answered 22/8, 2015 at 22:16 Comment(2)
Very clear. Thanks a lot. By the way, does anybody know why my question got a -1 from SO? Is it due to the inappropriate label "regex"? (If it is, sorry about that.)Betimes
@leo, the -1 is from a person and not SO itself. Either they didn't like that they got baited with the regex tag, or they didn't like how your initial version was formatted or they thought that you didn't put enough effort do understand this yourself before asking.Fluorescein

© 2022 - 2024 — McMap. All rights reserved.