如果您cmpthese
在Perl Benchmark模块的文档中阅读过,它会声明cmpthese
或timethese
可以与文本或子例程引用中的代码一起使用。文档似乎暗示这些形式是完全可以互换的:
# Use Perl code in strings...
timethese($count, {
'Name1' => '...code1...',
'Name2' => '...code2...',
});
# ... or use subroutine references.
timethese($count, {
'Name1' => sub { ...code1... },
'Name2' => sub { ...code2... },
});
我在使用字符串形式传递参数与使用cmpthese
. 中的值@array
没有通过,或者我有一个运行时错误。
我有以下代码:
#!/usr/bin/perl
use strict; use warnings;
use Benchmark qw(:all);
my @array = qw( first second third );
sub target {
my $str = $_[0];
print "str=$str\n";
}
sub control {
print "control: array[0]=$array[0]\n";
}
my $sub_ref=\⌖
my $control_ref=\&control;
print "\n\n\n";
# ERROR: array does not get passed...
cmpthese(1, {
'target text' => 'target(@array)',
'control 1' => 'control()',
});
# This is OK...
cmpthese(1, {
'sub code ref' => sub { target(@array) },
'control 2' => sub { control() },
});
# This is OK too...
cmpthese(1, {
'target sub' => sub { $sub_ref->(@array) },
'control 3' => sub { $control_ref->() },
});
# fixed paramenters work:
cmpthese(1, {
'target text fixed' => 'target("one", "two", "three")',
'control 4' => 'control()',
});
# Run time error...
cmpthese(1, {
'text code ref' => '$sub_ref->(@array)',
'control 5' => '$control_ref->()',
});
我使用的所有表格都可以正常使用,eval
所以我认为这可能是 Benchmark 的问题?我已经使用我所有的 google foo 来尝试找到两种形式之间的一些记录差异,但我不能。
有谁知道我上面的简单示例似乎没有按预期工作的原因?代码中的注释表明了我在 OS X、Perl 5.10.0 上遇到的问题。