【问题标题】:Need help in understanding perl tr command with /d需要帮助理解 perl tr 命令与 /d
【发布时间】:2015-08-22 23:30:44
【问题描述】:

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

#!/usr/bin/perl 

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

print "$string\n";

结果:

b b   b.

有人可以解释一下吗?

【问题讨论】:

    标签: perl translate


    【解决方案1】:

    /d 表示delete

    像这样发tr 是很不寻常的,因为它令人困惑。

    tr/a-z//d
    

    将删除所有“a-z”字符。

    tr/a-z/b/ 
    

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

    这里发生的情况是 - 因为您的音译没有在每一侧映射相同数量的字符 - 任何 没有 映射的内容都会被删除。

    所以你实际上在做的是:

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

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

    举例说明:

    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 -> ye 刚刚被删除。

    【讨论】:

    • 太棒了!非常感谢 Sobrique 的详细解释。感谢您的快速帮助。
    【解决方案2】:

    d 用于删除找到但未替换的字符。

    要删除不在匹配列表中的字符,可以通过将d 附加到tr 运算符的末尾来完成。

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

    打印:

     b  b
    

    字符串中不匹配的字符被删除,只替换匹配的字符(a替换为b)。

    【讨论】:

    • 感谢 serenesat 的快速帮助。正如 sobrique 解释的那样,我不知道 tr/b-z//d 的有效结果; tr/a/b/;
    猜你喜欢
    • 2016-07-08
    • 2016-04-01
    • 2017-02-07
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多