8. The While Loop
The while
loop enables you to repeat a sequence of statements an arbitrary number of times for as long a condition is met. The syntax is very similar to the if statement and will be introduced in the following example:
print "Please enter a number:\n"; $number=<>; chomp($number); $power_of_2 = 1; while ($power_of_2 < $number) { $power_of_2 *= 2; } print ("The first power of 2 that is " . "greater than this number is " , $power_of_2, "\n");
It is possible that a while
loop will not be executed at all, if the condition is not met right on the start.
The following program checks if a given string is made entirely of "a" characters:
print "Please enter a string:\n"; $string=<>; chomp($string); # Initialize all_as to TRUE $all_as = 1; # The first position in the string. $position = 0; while ($all_as && ($position < length($string))) { $char = lc(substr($string, $position, 1)); if ($char ne "a") { $all_as = 0; } # Increment the position $position++; } if ($all_as) { print "The string you entered is all A's!\n"; } else { print "At least one of the characters in the string " . "you entered is not \"A\".\n"; }