Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 845
jake9115 Avatar asked Oct 15 '13 20:10

jake9115


People also ask

How do you find the last element of a for loop?

Use Counter in PHP foreach Loop Use count() to determine the total length of an array. The iteration of the counter was placed at the bottom of the foreach() loop - $x++; to execute the condition to get the first item. To get the last item, check if the $x is equal to the total length of the array.

What is last if in Perl?

The last keyword is a loop-control statement that immediately causes the current iteration of a loop to become the last. No further statements are executed, and the loop ends. If LABEL is specified, then it drops out of the loop identified by LABEL instead of the currently enclosing loop.

How do you end a while loop in Perl?

In many programming languages you use the break operator to break out of a loop like this, but in Perl you use the last operator to break out of a loop, like this: last; While using the Perl last operator instead of the usual break operator seems a little unusual, it can make for some readable code, as we'll see next.

How does next statement differ from last statement in Perl?

next of Perl is the same as the continue in other languages and the last if Perl is the same as the break of other languages. redo probably does not have its counterpart. next will jump to the condition and if it is true Perl will execute the next iteration. last will quite the loop.


2 Answers

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

while(<>) {
    if(eof) {
        print "The last line of the file!\n";
    }
}
like image 156
AKHolland Avatar answered Sep 18 '22 01:09

AKHolland


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.

like image 30
Dave Sherohman Avatar answered Sep 19 '22 01:09

Dave Sherohman