http://qs321.pair.com?node_id=11140875


in reply to Perl's feature to determine, in current point of loop, that this is the last one?

There are so many ways to construct a loop. I'm not talking about syntax, i'm talking about the logic behind it and what the loop is trying to achieve. And even in a for() loop you might have some conditions that terminate the loop early (or restart the iterator).

For example, imagine a simple software that wants to run 100 loops of sending some data over the network. If the connection breaks, you'll have to restart from the beginning, or in some cases abort altogether. Let's write a small simulation:

#!/usr/bin/env perl use strict; use warnings; my $restartcount = 0; my $done = 1; for(my $i = 0; $i < 100; $i ++) { # Do your complex stuff here print "$i\n"; # Simulate some kind of random error # that requires a restart of the loop if(int(rand(100)+1) % 23 == 0) { print "Yada-Yada error, restarting loop\n"; $i = 0; $restartcount++; } # Simulate a condition that requires an abort if(int(rand(1000)+1) == 42) { print "Fatal error, aborting after $restartcount tries\n"; $done = 0; last; } } if($done) { print "Loop done\n"; print "Had to restart $restartcount times\n"; }

There is only a very small chance that the Perl interpreter is even theoretically capable of predicting when it is the last loop... until it exits the loop in one of three completely different ways. Depending on how borked your pseudo-random number generator is, it's theoretically possible that the script will never exit the loop. It's a classic halting problem. Alan Turing himself stated that it's impossible to predict the outcome.

perl -e 'use Crypt::Digest::SHA256 qw[sha256_hex]; print substr(sha256_hex("the Answer To Life, The Universe And Everything"), 6, 2), "\n";'