Data::Dumper::Simple 的条件加载不工作

Conditional load of Data::Dumper::Simple not working

我正在使用 Data::Dumper 和 Data::Dumper::Simple(DD 和 DDS)以脚本的详细模式打印哈希值,我希望能够与其他人共享它谁可能没有安装这些模块,所以我正在检查它们是否已加载。

在不检查模块是否成功加载的情况下,我将如何加载和使用它们的 MWE 是:

use strict;
use warnings;

use Data::Dumper;
use Data::Dumper::Simple;
$Data::Dumper::Sortkeys = 1;

my %testHash=();

warn Dumper(\%testHash);

打印:

$testHash = {};

使用 here 描述的方法首先检查模块是否已加载,只有在加载时才使用 Dumper 方法,我将代码重写为:

use strict;
use warnings;


my $dumperLoaded = 1;
my $rc;

$rc = eval
{
    require Data::Dumper;
    Data::Dumper->import();
    1;
};
if(!$rc)
{
    print "Data::Dumper not found\n";
    $dumperLoaded = 0;
}

$rc = eval
{
    require Data::Dumper::Simple;
    Data::Dumper::Simple->import();
    1;
};
if(!$rc)
{
    print "Data::Dumper::Simple not found\n";
    $dumperLoaded = 0;
}
if($dumperLoaded){
    $Data::Dumper::Sortkeys = 1;
}

my %testHash=();

if($dumperLoaded){
    warn Dumper(\%testHash);
}

现在我的输出是:

Name "Data::Dumper::Sortkeys" used only once: possible typo at temp.pl line 51.
$VAR1 = {};

现在哈希转储不显示变量名 testHash,就好像 DDS 没有加载一样。然而,我的脚本并没有抱怨它无法加载 DDS。我可以通过注释掉 use Data::Dumper::Simple; 在我的第一个 MWE 中复制它。

我的问题:为什么我的脚本的第二个版本,检查模块加载,只打印 DD,而不加载 DDS?

额外问题:在这样的条件模块加载场景中设置 SortKeys 的正确方法是什么?

谢谢。

Data::Dumper::Simple 是一个 source filter。必须在 Perl 的编译阶段加载源过滤器,否则它们将不会对脚本中的任何源代码执行它们的工作。

这个可能有效(未测试)有效:

my $dumperLoaded;
BEGIN { 
    $dumperLoaded = eval "use Data::Dumper::Simple;1" ||
                    eval "use Data::Dumper;1";
}

好的,首先 - 测试 return 代码很好,但实际上你最好使用 $@ 来检查 eval 是否有效。

例如:

eval { 
   require Data::Dumper;
   Data::Dumper -> import();
};
if ( $@ ) { 
   print "loading failed, error was: $@\n";
} 

但是你的问题的根源是:

The only thing exported is the Dumper() function.

Well, actually that's not really true. Nothing is exported. However, a source filter is used to automatically rewrite any apparent calls to C so that it just Does The Right Thing.

因为当您通过 require/import 加载 Data::Dumper::Simple 而不是 ,因此 Dumper 函数的重载是正在发生。

看着它 - 我实际上看不到调用 'alternate Dumper'

的简单方法