在使用/ d理解perl tr命令方面需要帮助

vik*_*s81 7 perl translate

我在网上看到了以下Perl示例.

#!/usr/bin/perl 

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

print "$string\n";
Run Code Online (Sandbox Code Playgroud)

结果:

b b   b.
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下吗?

Sob*_*que 8

/d表示delete.

这样做是很不寻常的tr,因为它令人困惑.

tr/a-z//d
Run Code Online (Sandbox Code Playgroud)

会删除所有'az'字符.

tr/a-z/b/ 
Run Code Online (Sandbox Code Playgroud)

将所有a-z字符音译为b.

这里发生的事情是 - 因为你的音译没有在每一侧映射相同数量的字符 - 任何映射的东西都会被删除.

所以你实际做的是:

tr/b-z//d;
tr/a/b/;
Run Code Online (Sandbox Code Playgroud)

例如,将所有as 音译为bs,然后删除任何其他内容(空格和点除外).

为了显示:

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

print "$string\n";
Run Code Online (Sandbox Code Playgroud)

警告:

Useless use of /d modifier in transliteration operator at line 5.
Run Code Online (Sandbox Code Playgroud)

和打印:

xyz cax sax on xyz max.
Run Code Online (Sandbox Code Playgroud)

如果您将其更改为:

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

print "$string\n";
Run Code Online (Sandbox Code Playgroud)

你改为:

xy cax sax on xy max.
Run Code Online (Sandbox Code Playgroud)

因此:t- > xh- > y.e刚被删除.