Perl::...terator(3pm)

πŸ“¦
version 1.0.4 Β· 4 versions
, in debian trixie, ubuntu resolute, ubuntu stonking

πŸ’– Perl::Critic::Policy::Community::LexicalForeachIterator β€” bestie edition πŸ’–

okay so this is Perl::...terator(3pm) from the User Contributed Perl Documentation section, and it's about a policy with a long name that's lowkey just here to make your foreach loops behave. sit with me, this one's short and sweet πŸŽ€


✨ NAME ✨

Perl::Critic::Policy::Community::LexicalForeachIterator β€” don't use undeclared foreach loop iterators. that's it. that's the whole vibe. πŸ’…


🌸 DESCRIPTION 🌸

so here's the tea β˜•. technically you can use a variable that's already been declared as the iterator for a foreach loop. it works! it compiles! but bestie... it will localize the variable to the loop, and its value gets reverted after the loop is done. so the variable you thought you were updating? yeah, it snaps right back like nothing happened. it's giving gaslighting. 😭

the fix is iconic and simple: always declare the loop iterator in the lexical scope of the loop with my. periodt.

foreach $foo (...) {...}    # not ok
for $bar (...) {...}        # not ok
foreach my $foo (...) {...} # ok
for my $bar (...) {...}     # ok

look at the bottom two. slayed. πŸ‘‘

fun fact: this policy is a subclass of the Perl::Critic core policy Perl::Critic::Policy::Variables::RequireLexicalLoopIterators, and it does the exact same thing β€” just wearing the "community" theme instead. same energy, different outfit. πŸ¦‹


🌈 AFFILIATION 🌈

this policy is part of Perl::Critic::Community. found family fr fr 🫢


πŸŽ€ CONFIGURATION πŸŽ€

ngl, there's nothing to tweak here. this policy is not configurable except for the standard options. it knows what it is and it's not taking suggestions. πŸ’œ


πŸ‘‘ AUTHOR πŸ‘‘

Dan Book, dbook@cpan.org β€” thank you for your service legend 🫑✨


Copyright 2015, Dan Book.

This library is free software; you may redistribute it and/or modify it under the terms of the Artistic License version 2.0. so like. go off, just respect the license bestie. πŸŽ€


πŸ’– SEE ALSO πŸ’–

  • Perl::Critic β€” the mothership. go say hi. πŸ›Έ

and that's the whole page!! this beauty shipped as perl v5.40.1 on 2025-03-22 β€” mwah, no notes, k bye πŸ’…πŸŒΈβœ¨

πŸ“¦ where this page comes from