Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

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

by cavac (Priest)
on Jan 26, 2022 at 13:09 UTC ( #11140875=note: print w/replies, xml ) Need Help??


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";'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11140875]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2022-05-23 11:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (82 votes). Check out past polls.

    Notices?