Perl + PerlCritic |循环迭代器不是词法的

Perl + PerlCritic | loop iterator is not lexical

我有这个代码

...
    my $line = '';
        foreach $line ( split( /\n/x, $raw ) ) {
            chomp $line;
            my ( $key, $val ) = split( /=/x, $line );
            $param{$key} = $val;
        }
...

perlcritic 检查后,我收到消息 "Loop iterator is not lexical." 怎么了?

我可以用

 #my $line = '';
            foreach my $line ( split( /\n/x, $raw ) )

但是为什么呢? :)

PerlCritic 希望循环变量只在循环内有作用域,即变量在循环结束后不应该存在。这可能被认为是过分的 purist/pedantic,但我倾向于同意,并且通常也以这种方式编写我的 Perl 代码。

此外,this looks like a configurable option

来自 cpan Perl::Critic::Policy::Variables::RequireLexicalLoopIterators!

This may not seem like a big deal until you see code like

my $bicycle;
for $bicycle (@things_attached_to_the_bike_rack) {
    if (
            $bicycle->is_red()
        and $bicycle->has_baseball_card_in_spokes()
        and $bicycle->has_bent_kickstand()
    ) {
        $bicycle->remove_lock();

        last;
    }
}

if ( $bicycle and $bicycle->is_unlocked() ) {
    ride_home($bicycle);
}

which is not going to allow you to arrive in time for dinner with your family because the $bicycle outside the loop is not changed by the loop. You may have unlocked your bicycle, but you can't remember which one it was.