Is it possible to determine if the current iteration of the while loop is the last in perl?

I never thought it was possible, but I read some conflicting comments and thought that I would ask experts.

If I progress through a while loop that reads a file line by line, is there a way to execute some code if the current iteration is the last iteration in the loop? I understand that I could just put this code right after the while loop, so that the code will execute after the last line, but I'm just wondering if the iteration method has any way to detect it.

Thanks!

+6
source share
2 answers

In the special case, when you read the file, yes.

while(<>) { if(eof) { print "The last line of the file!\n"; } } 
+6
source

Although there may be certain special cases in which it can be determined that the current iteration is the last, in the general case this is not possible. Trivial example:

 while (rand() < 0.99) { print "Hasn't ended yet\n"; } 

Since it is impossible to predict what the next random number will be, it is obvious that it is impossible to determine whether any iteration will be the last iteration.

+4
source

Source: https://habr.com/ru/post/956017/


All Articles