Perl::Critic::Policy::Community::WhileDiamondDefaultAssignment(3pm)

Perl::Critic::Policy::Community::WhileDiamondDefaultAssignment3pm

Don't use while with implicit assignment to $_

Overview

The diamond operator "<>" (or "<<>>"), and functions readline(), readdir(), and each() are extra magical in a while condition: if it is the only thing in the condition, it will assign its result to $_, but it does not localize $_ to the while loop. (Note, this also applies to a "for (;<>;)" construct.) This can unintentionally confuse outer loops that are already using $_ to iterate. In addition, using $_ at all means that your loop can get confused by other code which does not politely localize its usage of the global variable. To avoid these possibilities, assign the result of the diamond operator or these functions to an explicit lexical variable.

  while (<$fh>) { ... }                   # not ok
  while (<<>>) { ... }                    # not ok
  ... while <STDIN>;                      # not ok
  for (;<>;) { ... }                      # not ok
  while (readline $fh) { ... }            # not ok
  while (readdir $dh) { ... }             # not ok
  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

Affiliation

This policy is part of Perl::Critic::Community.

Configuration

This policy is not configurable except for the standard options.

Releases

2 releases since Debian 12 (Bookworm); the text changed 1 time.

  1. 12
  2. 13

Author

Dan Book, "[email protected]"

From libperl-critic-community-perl 1.0.4-1 in Debian 13 (Trixie). Parsed by carta from the page's man source.