Perl + PerlCritic | loop iterator is not lexical

1.8k Views Asked by At

I have this code

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

After perlcritic checking, i get messsage "Loop iterator is not lexical." Whats wrong?

I can use

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

but why? :)

2

There are 2 best solutions below

1
Jim Garrison On BEST ANSWER

PerlCritic wants the loop variable to only have a scope within the loop, i.e. the variable should not exist after the end of the loop. This could be considered excessively purist/pedantic, but I tend to agree, and usually write my Perl code that way as well.

Also, this looks like a configurable option

0
shalk On

from 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.