10

I would like to use $a and $b variables in my anonimous binary functions like it is done in sort {$a <=> $b} (1, 2, 3) but I can not figure out why code like

#!/usr/bin/env perl
use strict;
use warnings;

Foo::Bar(sub { $a + $b });

package Foo;
sub Bar {
    my ($function) = @_; 

    for my $i (1, 2, 3) {
        local ($a, $b) = ($i, $i);
        print $function->() . "\n";
    }
}    

does not work. While

#!/usr/bin/env perl
use strict;
use warnings;

Foo::Bar(sub { $_ });

package Foo;
sub Bar {
    my ($function) = @_; 

    for my $i (1, 2, 3) {
        local $_ = $i;
        print $function->() . "\n";
    }
}

works fine.

What am I doing wrong?

4

2 回答 2

14

$a并且$b是特殊的包变量。你是Foo::Bar从你的main包中调用的,所以你需要设置它$main::a$main::b让它工作。您可以使用caller来获取调用包的名称。这应该有效:

#!/usr/bin/env perl
use strict;
use warnings;

Foo::Bar(sub { $a + $b });

package Foo;
sub Bar {
    my ($function) = @_; 
    my $pkg = caller;

    for my $i (1, 2, 3) {
        no strict 'refs';
        local *{ $pkg . '::a' } = \$i;
        local *{ $pkg . '::b' } = \$i;
        print $function->() . "\n";
    }
}    
于 2012-01-02T18:42:03.983 回答
0

以防万一有人感兴趣,从List::MoreUtils::PP v.0.428 复制并粘贴(截至 2017 年 12 月):

# begin copyrighted content
sub reduce_u(&@)
{
    my $code = shift;

    # Localise $a, $b
    my ($caller_a, $caller_b) = do
    {
        my $pkg = caller();
        no strict 'refs';
        \*{$pkg . '::a'}, \*{$pkg . '::b'};
    };

    local (*$caller_a, *$caller_b);
    *$caller_a = \();
    for (0 .. $#_)
    {
        *$caller_b = \$_[$_];
        *$caller_a = \($code->());
    }

    ${*$caller_a};
}
# end copyrighted content

它仅在受 影响的区域与上面的示例不同no strict 'refs';。可能根本不严格就做不到。

于 2017-12-25T09:22:23.480 回答