in reply to $_ getting clobbered by inner loop.

You can nest for loops because each for loop localizes its iterator. However, while doesn't localize $_ (or even know anything about it). You'll need to do it explicitly.

Replies are listed 'Best First'.
Re^2: $_ getting clobbered by inner loop.
by dbanas (Novice) on Apr 09, 2008 at 14:34 UTC
    Ah, I see. Thanks. Can you explain the philosophy behind this design choice? That is, does localizing $_ in for loops, but not in while loops, provide something useful to Perl? Thanks. -db

      Localizing $_ in a while loop would cause any changes to that variable to mysteriously be lost when you exit the while.

      Code should not mess around with things that are not its concern, since that would generate unintended and unexpected side effects. The while loop does not inherently use $_, so therefore it should not localize or otherwise muck up $_.

      The same reasoning would explain why a while loop does not automatically localize @test_files as well.

      Because $_ has nothing to do with while loops. You're looking at one specific while loop (while (defined($_ = <FILE>)) when asking that question, but while is used in many other ways too. For example, why should Perl localize $_ in while (@todo)? Or in while (my ($key, $val) = each %hash)?
      larry he is not