Elyse M. Grasso wrote:
But you need to process the file while you haven't reached the end yet, or until you reach the end. And I can't think of an occasion where I knew going in what the length of the file I was processing was going to be. I suppose foreach might make sense if you sucked in the whole file at once and then processed the individual lines, but I've seldom been in situations where I could assume it was safe to do that. (Data expands to fill the space available, plus 10 %... and the production data file is always bigger than they told you it would be.)

The same goes for database queries: you loop while the query is returning data or until it stops returning data.

Foreach implies to me that you want to do the same thing, or something very similar, to each of the things you are processing. But in handling the lines of a file or the records returned by a query you may in fact want to throw many of them away, or handle various subgroups of data in different ways.

That doesn't make any difference as far as I'm concerned. foreach (or for in Perl 6) implies to me that you have a list of things and you're going to look at each of them in turn. Whether you do the same thing to them or not is to my mind irrelevant, you're stepping over a list item by item. for is, to me, ideally suited for anything where you're looking at a sequence of things one at a time - reading lines from a file fits that perfectly.


Perhaps the reason the indeterminate length of a file doesn't bother me is because I'm a Haskell programmer, where everything is lazy and recursing over lists is about the only way to get any kind of looping at all. Iterating over something of indeterminate length really doesn't bother me :-)

Something like the C++y

while(!in.eof()) {
...
}

Is attractive in its way, but I'd rather have something more convenient, and I think doing a for over a conceptual list (as in it's not really a list, but it's behaving kind of like one in this context) of lines in the file is infinitely better.

One can also view the results of a database query as a list of rows returned which you then look at one at a time. In fact, I find that far more natural than fetching until there are none left.

Of course, you're still really doing that behind the scenes.

Reply via email to