Jim Gibson wrote:
Tiago Hori wrote:

Just so I make sure I understand it correctly: So every time I use a while
(<FILEHANDLE>) loop each line of input from the file gets assigned to $_ in
each iteration of the loop?

Almost.

<>  is an operator. Each time<FILEHANDLE>  is evaluated, a line is read from
the file and assigned to the $_ variable. This is regardless of whether or
not<FILEHANDLE>  appears in the condition of a while statement.

 From 'perldoc perlop' (search for "I/O Operators"):

"In scalar context, evaluating a filehandle in angle brackets yields the
next line from that file (the newline, if any, included), or "undef" at
end-of-file or on error.  When $/ is set to "undef" (sometimes known as
file-slurp mode) and the file is empty, it returns '' the first time,
followed by "undef" subsequently."

That is simply wrong. A filehandle within angle brackets is equivalent
to readline(filehandle). If it is executed in void context the data from
the file will be lost. Yes, as the documentation says, the operator
"yields the next line from that file", but outside a while loop it has
to be explicitly assigned to a variable or it will be discarded.

Tiago is exactly right in what he says: the implict assignment to $_ (as
well as a test for definedness) happens only within a while
condition.

  while (<FILEHANDLE>) {
    :
  }

is identical to

  while (readline FILEHANDLE) {
    :
  }

which compiles as

  while (defined($_ = readline FILEHANDLE)) {
    :
  }

Rob

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to