Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

tr

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.)

like image 804
leo Avatar asked Aug 22 '15 22:08

leo


People also ask

What is the use of TR () function in Perl?

The tr operator in Perl translates all characters of SearchList into the corresponding characters of ReplacementList. Here the SearchList is the given input characters which are to be converted into the corresponding characters given in the ReplacementList.

What does =~ mean in Perl?

=~ is the Perl binding operator. It's generally used to apply a regular expression to a string; for instance, to test if a string matches a pattern: if ($string =~ m/pattern/) {

How do I match a string in Perl?

m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.

What is the meaning of $1 in Perl regex?

$1 equals the text " brown ".


1 Answers

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).

like image 147
ndnenkov Avatar answered Sep 23 '22 19:09

ndnenkov