需要帮助理解/d 的 perl tr 命令 [英] Need help in understanding perl tr command with /d
问题描述
我在网上遇到了以下 Perl 示例.
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";
结果:
b b b.
有人可以解释一下吗?
推荐答案
/d
表示 delete
.
做这样的 tr
很不寻常,因为它令人困惑.
It's quite unusual to do a tr
like that because it's confusing.
tr/a-z//d
将删除所有 'a-z' 字符.
would delete all 'a-z' characters.
tr/a-z/b/
会将所有 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.
所以你有效地做的是:
tr/b-z//d;
tr/a/b/;
例如将所有 a
s 音译为 b
s,然后删除其他任何内容(空格和点除外).
E.g. transliterating all the a
s to b
s and then deleting anything else (except spaces and dots).
举例说明:
use strict;
use warnings;
my $string = 'the cat sat on the mat.';
$string =~ tr/the/xyz/d;
print "$string\n";
警告:
Useless use of /d modifier in transliteration operator at line 5.
和打印:
xyz cax sax on xyz max.
如果您将其更改为:
#!/usr/bin/perl
use strict;
use warnings;
my $string = 'the cat sat on the mat.';
$string =~ tr/the/xy/d;
print "$string\n";
你会得到:
xy cax sax on xy max.
因此:t
-> x
和 h
-> y
.e
刚刚被删除.
And thus: t
-> x
and h
-> y
. e
just gets deleted.
这篇关于需要帮助理解/d 的 perl tr 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!