On Dec 26, 2004, at 4:34 AM, John Delacour wrote:

At 10:44 pm -0500 25/12/04, Lola Lee wrote:

This script has you count words in a file. The line where one is supposed to read in the file being counted is like so:

while (defined($line = <>))

However, when I type this in: perl countwords.pl history.txt

Nothing happens.


The line you quote simply puts each line of a putative file into the scalar variable $line. What "happens" will depend on how you deal with $line and where you print your results.

Supposing that countwords.pl is a script something like the one below and that history.txt is a file in the same directory (say your home directory), then you will get output in the terminal as below when you run your command. I personally would substitute for your line:

  foreach $line (<>)

which does the same thing and, to me at least, is simpler and clearer.

It doesn't quite do the same thing. The 'while' loop will read one line, then process it, then read the next line, then process it, and so on. The 'foreach' loop will read all the lines into memory, then process each of them one by one. So if it's a large file, you'll have the whole thing in memory at once.


The simplest, if you like using the default variable $_, is this:

  while (<>) {
    ...
  }

which is shorthand for:

  while (defined($_ = <>)) {
    ...
  }

 -Ken



Reply via email to