代码之家  ›  专栏  ›  技术社区  ›  dawg

Perl:cmpthese文本与传递参数的匿名子问题

  •  2
  • dawg  · 技术社区  · 14 年前

    如果你读到 cmpthese Perl Benchmark 模块的文档说明 这些 timethese 可与文本或子例程引用中的代码一起使用。文件似乎暗示这些表格是完全可互换的:

    # Use Perl code in strings...
    timethese($count, {
    'Name1' => '...code1...',
    'Name2' => '...code2...',
    });
    # ... or use subroutine references.
    timethese($count, {
    'Name1' => sub { ...code1... },
    'Name2' => sub { ...code2... },
    });
    

    对于字符串形式的传递参数和子例程引用形式的传递参数,我有困难 这些 . 中的值 @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 所以我认为这可能是基准测试的问题?我用我所有的google foo试图找出这两种表单之间的一些文档差异,但我做不到。

    有没有人知道我上面的简单例子似乎没有达到预期效果的原因?代码中的注释指出了我在OSX Perl5.10.0上遇到的问题。

    2 回复  |  直到 14 年前
        1
  •  5
  •   Eric Strom    14 年前

    我没有看太多细节,但我猜 Benchmark 将字符串转换成代码,词法变量 @array 不在范围内。如果你能 @阵列 一个 our 变量。

    但总的来说,我发现仅仅使用代码引用更容易。

        2
  •  6
  •   mob    14 年前

    文本传递给 cmpthese timethese 得到支持 eval 深藏在基准的内心深处的陈述。除非文本中的参数是文本或全局变量,否则它们在计算时将不在作用域中,并且您将得到一个运行时错误。

    使用参数的匿名子版本为您的参数提供词法闭包,并且一切都会很好。