Need help understanding the perl tr command with / d

I came across the following Perl example on the Internet.

#!/usr/bin/perl $string = 'the cat sat on the mat.'; $string =~ tr/az/b/d; print "$string\n"; 

result:

 bb b. 

Can someone explain how?

+5
source share
2 answers

/d stands for delete .

It is quite unusual to make tr so, because it is confusing.

 tr/az//d 

will remove all az characters.

 tr/az/b/ 

transliterates all az characters to b .

What happens here, although there is - because your transliteration does not display the same number of characters on each side - everything that is not displayed is deleted.

So what you do is:

 tr/bz//d; tr/a/b/; 

eg. transliterating all a to b and then deleting anything else (except spaces and dots).

To illustrate:

 use strict; use warnings; my $string = 'the cat sat on the mat.'; $string =~ tr/the/xyz/d; print "$string\n"; 

Warns:

 Useless use of /d modifier in transliteration operator at line 5. 

and prints:

 xyz cax sax on xyz max. 

If you change this to:

 #!/usr/bin/perl use strict; use warnings; my $string = 'the cat sat on the mat.'; $string =~ tr/the/xy/d; print "$string\n"; 

Instead, you will get:

 xy cax sax on xy max. 

And thus: t β†’ x and h β†’ y . e simply deleted.

+6
source

d used to delete found but not replaced characters.

To remove characters that are not in the match list, you can do this by adding d to the end of the tr statement.

 #!/usr/bin/perl my $string = 'my name is serenesat'; $string =~ tr/az/bcd/d; print "$string\n"; 

Print

  bb 

Non-matching characters in the string are deleted, and only the corresponding character is replaced ( a replaced by b ).

+3
source

All Articles