批评 : eval "require $module";

标签 perl perl-critic

在挖掘一些旧的源代码时,我看到了以下内容:

my $module = $some{module};
eval "require $module";
die "Bad module\n$@" if $@;

虽然我了解代码的作用,但它会尝试“要求”一个模块并在它不成功时死掉 - 批评者提示它

Expression form of "eval" at line 331, column 13. See page 161 of PBP. (Severity: 5)



不幸的是我还没有 PBP 书,所以想知道上面的正确方法是什么......

此外,在同一来源中发现:
sub test_repo_file {
    my($self, $repo, $test) = @_;
    my $abspath = repo_abs_path($repo);
    return "eval -$test $abspath";
}

这里不明白是什么解决了“eval”,perlcritic 再次提示“string eval”......

有人可以解释一下关于“字符串评估”的基本要点以及如何正确编写上述内容吗?

最佳答案

运行perlcritic --verbose '%d\n'也会给你解释:

The string form of `eval' is recompiled every time it is executed, whereas the block form is only compiled once. Also, the string form doesn't give compile-time warnings.

   eval "print $foo";        # not ok
   eval {print $foo};        # ok


适用于第一种情况。

第二种情况不会为我生成任何消息。岂不是更
return eval "-$test $abspath"

你不能在这里使用 block 评估。您应该验证 $test 确实包含它应该包含的内容
$test =~ /^[a-z]$/i

并避免评估 $abspath:
eval "-$test \$abspath"

如果您对此感到满意,则可以添加
## no critic

到行尾。

关于批评 : eval "require $module";,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29661885/

相关文章:

perl - 使用 Perl 的 WWW::Mechanize 发送自定义 cookie(并查看自然设置的 cookie)

windows - 什么是适用于 Windows 的免费 Perl IDE?

perl - 如何在 Windows 上的 Komodo IDE 5.1 中启用 PerlCritic 支持?

perl - 我们如何使用 Perl::Tidy 或 Perl::Critic 捕捉旁注?

xml - 访问 XML 文件中的元素属性

perl - 我们如何在 Perl CGI Web 应用程序中维护 session ?

perl - 如何在 osx 上安装 perl 评论家?

Perl::Critic "Don' t use this method"-type rule

Perl 使用变量来引用模块会弄乱传递参数

perl - 我是否需要在调用 Win32::OLE->LastError 时捕获错误?