6

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!

2
  • 1
    See Perl's eof.
    – Kenosis
    Oct 15, 2013 at 20:17
  • 4
    Also note the distinction between eof and eof() - In a while(<>) loop, the shorter one may be true multiple times @ARGV has multiple files, and the longer one returns true only once.
    – vapace
    Oct 15, 2013 at 20:37

2 Answers 2

6

In the special case where you are reading from a file, yes.

while(<>) {
    if(eof) {
        print "The last line of the file!\n";
    }
}
2
  • 1
    @HunterMcMillen, in the general case, how would the loop know that the condition will be false the next time it's evaluated?
    – cjm
    Oct 15, 2013 at 20:41
  • 1
    @jake9115: All it really does is move the print "The last line of the file!\n" inside the while loop, which some would say is a distraction.
    – Borodin
    Oct 15, 2013 at 22:38
4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.