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

£可爱£侵袭症+ 提交于 2019-12-08 20:21:15

问题


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!


回答1:


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

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



回答2:


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.



来源:https://stackoverflow.com/questions/19390020/is-it-possible-to-detect-if-the-current-while-loop-iteration-is-the-last-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!