Perl::...gnment(3pm)

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

πŸ¦‹ NAME πŸ¦‹

okay so bestie, welcome to the manual page for Perl::Critic::Policy::Community::WhileDiamondDefaultAssignment β€” which lives on the Perl::...gnment(3pm) page πŸ’…

tl;dr: don't use while with implicit assignment to $_. that's it, that's the whole vibe. periodt. ✨


😭 DESCRIPTION 😭

so here's the tea, and it's kind of unhinged honestly. the diamond operator < > (or <<>>), plus the functions readline(), readdir(), and each() β€” they get extra magical when they show up in a while condition. like, if one of them is literally the only thing in that condition, it will assign its result to $_ for you. cute, right? NO. because it does not localize $_ to the while loop. πŸ™ˆ

(and yeah, this also applies to a for (;<>;) construct, so don't think you're slick.)

the way this can unintentionally confuse outer loops that are already using $_ to iterate?? it's giving chaos. and on top of that, using $_ at all means your loop can get confused by other code which does not politely localize its usage of the global variable. rude of them, honestly.

so to dodge all of these possibilities, just assign the result of the diamond operator or these functions to an explicit lexical variable. slay, problem solved, main character energy. πŸ‘‘

here's the vibe check β€” these are not ok:

while (<$fh>) { ... }                   # not ok
while (<<>>) { ... }                    # not ok
... while <STDIN>;                      # not ok
for (;<>;) { ... }                      # not ok
while (readline $fh) { ... }            # not ok
while (readdir $dh) { ... }             # not ok

and these are ok, obsessed, ate, no notes:

while (my $line = <$fh>) { ... }        # ok
while (my $line = <<>>) { ... }         # ok
... while $line = <STDIN>;              # ok
for (;my $line = <>;) { ... }           # ok
while (my $line = readline $fh) { ... } # ok
while (my $dir = readdir $dh) { ... }   # ok

see the difference? lexical variable. every time. it's literally that simple bestie πŸ’–


πŸŽ€ AFFILIATION πŸŽ€

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


βš™οΈ CONFIGURATION βš™οΈ

ngl this one is not configurable except for the standard options. so... no customizing your way out of this one, sorry. it is what it is. πŸ’€


✍️ AUTHOR ✍️

Dan Book, dbook@cpan.org β€” iconic, thank you for your service 🌸


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


πŸ‘€ SEE ALSO πŸ‘€

  • Perl::Critic

and that's the whole page, bestie!! 🧚 this lil masterpiece was brought to you by perl v5.40.1, dated 2025-03-22 β€” go forth and localize your $_, ily, bye!! πŸ’œπŸ“βœ¨

πŸ“¦ where this page comes from