gpt4 book ai didi

perl - 需要帮助理解/d 的 perl tr 命令

转载 作者:行者123 更新时间:2023-12-04 10:49:38 24 4
gpt4 key购买 nike

我在网上遇到了以下 Perl 示例。

#!/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 是很不寻常的像那样,因为它令人困惑。

tr/a-z//d

将删除所有 'a-z' 字符。
tr/a-z/b/ 

会音译所有 a-z字符到 b .

不过,这里发生的事情是 - 因为您的音译不会在每一侧映射相同数量的字符 - 任何未映射的内容都将被删除。

所以你有效地做的是:
tr/b-z//d;
tr/a/b/;

例如。音译所有 a转至 b s 然后删除其他任何内容(空格和点除外)。

为了显示:
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 -> xh -> y . e只是被删除。

关于perl - 需要帮助理解/d 的 perl tr 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30710164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com