in reply to Line number problem with foreach

    This is equivalent to while(<>) { ... }
use strict; use warnings; open my $fh, "test.txt" or die $!; foreach (;<$fh>;){ print " $. :$_ \n"; }

Replies are listed 'Best First'.
Re^2: Line number problem with foreach
by roho (Bishop) on Feb 28, 2009 at 21:56 UTC
    Very interesting. I tried your code, and you are right. $. contains the current line number for each record in the input file. My question is "Why does the presence of semi-colons around the diamond make this work? Do they force scalar mode instead of list mode? Does this mean the file is NOT slurped into a list all at once?

    "Its not how hard you work, its how much you get done."

      In the C-style for-loop
      foreach (;<$fh>;) { print " $. :$_ \n"; }
      the initialization and finalization clauses of the loop (the parts before the first semicolon and after the second semicolon, respectively) are empty. The only clause specified is the conditional clause (between the two semicolons). When the  <> or readline operator is evaluated in the scalar context of the conditional, it returns a single line at a time until the file is exhausted, when it returns undef.

      This is equivalent to reading  <$fh> in a while-loop.

Re^2: Line number problem with foreach
by churchmice (Initiate) on Feb 28, 2009 at 13:43 UTC
    Well, this is indeed a for loop