PERL5.26.1 带插值的 eval tr 运算符(camel book 第 76 页的示例)不起作用

标签 perl eval tr

尝试在 tr 运算符语句中使用变量作为模式。 Camel 书第 76 页说要像这样使用 eval:

eval "tr/$oldlist/$newlist/";

在 Linux 上使用 perl_5.26.1 有两个问题: a) 使用上面的引号 eval 会给出错误消息。 所以你必须用大括号将它放在一个 block 中。 b)即使在大括号中也不起作用。我究竟做错了什么?这是代码和输出:

    $kards = -99;
    $bad="AKQJT98765432KKKK";
    $card='K';
    eval {print "eval is testing for $card in $bad \n"; 
           $kards = $bad =~ tr/$card//; # tried also tr/$card/$card/; same result.
          };
    print "Num of $card in $bad = $kards \n";
    $king = $bad =~ tr/K//;
    print "Num of K in $bad is = $king \n";
=cut    
    Returns the following:
eval is testing for K in AKQJT98765432KKKK 
Num of K in AKQJT98765432KKKK = 0 
Num of K in AKQJT98765432KKKK is = 5 
    
=end 

最佳答案

您想通过 tr 从字符串中删除一组字符,该组字符是在运行时确定的,并获取其中删除了多少个字符?

由于 tr 不执行 the documentation 和您正在查看的《Programming Perl》书中所述的变量插值,是的,您必须将 eval 与字符串一起使用论据:

#!/usr/bin/env perl
use warnings;
use strict;
use feature qw/say/;

my $cards = "K";
my $str = "A12K34567890JQK";
my $count = eval "\$str =~ tr/$cards//";
say $count;

将生成2(5.22或5.32上没有警告;没有在任何地方安装5.26来确认)。请注意,必须转义 tr 在字符串中操作的变量中的 $,这样就不会首先对其进行插值。


不过,您可以使用 s// 来执行此操作,而无需使用潜在危险的 eval:

my $count = $str =~ s/[\Q$cards\E]//g;

关于PERL5.26.1 带插值的 eval tr 运算符(camel book 第 76 页的示例)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64073345/

相关文章:

javascript - 如果eval()无法评估给定的字符串,则显示 “Syntax Error”

linux - 使用 tr 命令将单个单词变为大写

bash - tr -d [=,=] 的作用是什么?

perl - ^= 运算符在 Perl 中有什么作用?

perl - 为什么在标量上下文中Perl文件glob()无法在循环外工作?

perl - 如何防止 PerlTidy 对齐我的作业?

perl - grep 在大文件上表现不佳,有没有替代方法?

actionscript-3 - AS3 : "Variable [x] is not defined" error when using getDefinitionByName()

javascript - 规避评估

linux - bash 在给定模式之前用逗号查找并替换 "enter"