Infinite Loops

Learn how an infinite loop might occur in a while or a for loop in Perl in this lesson.

What are infinite loops ?

One common programming mistake is to create an infinite loop. An infinite loop refers to a loop, which under certain valid (or at least plausible) input, will never exit.

Note: Beginner programmers should be careful to examine all the possible inputs into a loop to ensure that for each such set of inputs, there is an exit condition that will eventually be reached.

Compilers, debuggers, and other programming tools can sometimes help the programmer in detecting infinite loops.

In general, it is not always possible to automatically detect an infinite loop. This is known as the halting problem (an open theoretical computer science problem).

Example of an infinite loop

Down below is an example of an infinite loop.

Press + to interact
$a = 1;
# the while condition will always be met as it will always return true
while($a){
print "Infinite loop\n";
}

When we run the code above, it will print “Infinite loop” without stopping because the condition statement in the while loop will always resolve to true. There is no point at which the loop condition will evaluate to false hence we’ll get stuck in an infinite loop, ​and the code will​ execute forever. Similarly, the for loop given below runs infinite time without stopping.

Press + to interact
for ($i = 0; $i < 1; ){ # as the condtion always met and never ends
print "Infinite loop"
}