Need help in understanding perl tr command with /d

三世轮回 提交于 2019-12-04 01:05:55

问题


I came across the following Perl example on the web.

#!/usr/bin/perl 

$string = 'the cat sat on the mat.';
$string =~ tr/a-z/b/d;

print "$string\n";

result:

b b   b.

Can someone please explain how ?


回答1:


/d denotes delete.

It's quite unusual to do a tr like that because it's confusing.

tr/a-z//d

would delete all 'a-z' characters.

tr/a-z/b/ 

would transliterate all a-z characters to b.

What's happening here though is - because your transliteration doesn't map an equal number of character on each side - anything that doesn't map is deleted.

So what you're effectively doing is:

tr/b-z//d;
tr/a/b/;

E.g. transliterating all the as to bs 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 that to:

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

print "$string\n";

You get instead:

xy cax sax on xy max.

And thus: t -> x and h -> y. e just gets deleted.




回答2:


d is used to delete found but not replaced characters.

To remove the characters which are not in the matching list can be done by appending d to the end of the tr operator.

#!/usr/bin/perl 

my $string = 'my name is serenesat';
$string =~ tr/a-z/bcd/d;
print "$string\n";

Prints:

 b  b

Not matching characters in the string is removed, and only the matching character replaced (a replaced with b).



来源:https://stackoverflow.com/questions/30710164/need-help-in-understanding-perl-tr-command-with-d

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!