PerlCritic 示例:循环迭代器不是词法的
Posted
技术标签:
【中文标题】PerlCritic 示例:循环迭代器不是词法的【英文标题】:PerlCritic example: loop iterator is not lexical 【发布时间】:2022-01-17 21:50:11 【问题描述】:在调试一些较旧的 perl 代码时,我使用 perlcritic 作为一种发现错误的方法。 我经常偶然发现这个“循环迭代器不是词法”策略: Perl::Critic::Policy::Variables::RequireLexicalLoopIterators 而且它从来都不是错误。 当我在测试程序中实现作者的示例时,我似乎没有重现它试图解决的问题:
#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;
my $bicycle = is_red => 1, has_baseball_card_in_spokes => 1, has_bent_kickstand => 1, locked => 1;
my $bicycle1 = is_green => 1, has_baseball_card_in_spokes => 1, has_bent_kickstand => 1, locked => 1;
my $bicycle2 = is_blue => 1, has_baseball_card_in_spokes => 0, has_bent_kickstand => 0, locked => 1;
my @things_attached_to_the_bike_rack = ($bicycle,$bicycle1,$bicycle2);
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->locked = 0;
last;
if ( $bicycle and !$bicycle->locked )
print "riding home in time for dinner\n";
诚然,我没有用函数创建一个有福的对象,而是一个哈希引用,所以它可能与 Perl 中的对象有关。 即使我重新安排阵列的顺序,我每次都会及时回家吃晚饭。 所以我肯定遗漏了一些明显的东西,我想要一个可重现的例子来说明这是一个问题的情况。
我知道有old questions about this,但我想知道这是否仍然是 2021 年末的相关政策。
【问题讨论】:
【参考方案1】:您的代码与策略示例不同。您的代码在循环外为 $bicycle
分配了一个值,而策略示例没有。
以下代码更能代表策略示例的意图:
use strict;
use warnings;
use diagnostics;
my $bicycle0 = is_red => 1, has_baseball_card_in_spokes => 1, has_bent_kickstand => 1, locked => 1;
my $bicycle1 = is_green => 1, has_baseball_card_in_spokes => 1, has_bent_kickstand => 1, locked => 1;
my $bicycle2 = is_blue => 1, has_baseball_card_in_spokes => 0, has_bent_kickstand => 0, locked => 1;
my @things_attached_to_the_bike_rack = ($bicycle0, $bicycle1, $bicycle2);
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->locked = 0;
last;
if ( $bicycle and !$bicycle->locked )
print "riding home in time for dinner\n";
当我运行它时,我没有看到 riding home in time for dinner
消息,正如我在运行您的原始代码时所看到的那样。
【讨论】:
以上是关于PerlCritic 示例:循环迭代器不是词法的的主要内容,如果未能解决你的问题,请参考以下文章