On Monday 06 December 2004 01:26 pm, Smylers wrote: > I think that C<for> reads much better than C<while> for English-ness. > Having taught Perl 5 beginners that C<foreach> can be used to iterated > over each item in a list, many of them then instinctively try to use the > same keyword for iterating over each line in a file. (Which of course > works -- albeit inefficiently and umidiomatically -- so they don't > bother looking any further.) > > To me C<for> makes sense when you've got a pile of stuff you're > intending to process (such as array items or lines in a file), and > C<while> makes sense when you're waiting for a condition (such as the > user correctly entering her/his password) and you couldn't possibly know > in advance how many times you'll be looping. > > Smylers > > 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. -- Elyse Grasso http://www.data-raptors.com Computers and Technology http://www.astraltrading.com Divination and Science Fiction