Reputation: 4084
I never thought this was possible, but read some conflicting comments and thought I would ask the experts.
If I am progressing through a while loop that is reading a file line by line, is there a way to execute some code if the current iteration will be the final iteration in the loop? I understand that I could simply place this code immediately after the while loop, so that the code would execute after the last line, but I was just wondering if the iteration has any way of detecting it's position.
Thanks!
Upvotes: 6
Views: 1370
Reputation: 46187
While there may be certain special cases in which is it possible to determine that the current iteration is the last, it is not possible in the general case. A trivial example:
while (rand() < 0.99) {
print "Hasn't ended yet\n";
}
Since it is not possible to predict what the next random number will be, it is clearly not possible to know whether any given iteration will be the final iteration.
Upvotes: 4
Reputation: 4445
In the special case where you are reading from a file, yes.
while(<>) {
if(eof) {
print "The last line of the file!\n";
}
}
Upvotes: 6