while loop in perl

www.igi‮oc.aeditf‬m

The while loop is a common loop construct in Perl that allows you to execute a block of code repeatedly as long as a certain condition is true.

Here's the basic syntax of the while loop in Perl:

while (condition) {
    # block of code to be executed repeatedly
}

The loop will continue to execute as long as the condition is true. If the condition is false, the loop will terminate and execution will continue with the next statement after the loop.

Here's an example of a while loop that prints the numbers from 1 to 10:

my $i = 1;
while ($i <= 10) {
    print "$i\n";
    $i++;
}

In this example, the variable $i is initialized to 1. The while loop continues as long as $i is less than or equal to 10. Inside the loop, the print statement prints the value of $i, and the variable $i is incremented by 1 after each iteration of the loop.

You can use any valid Perl expression as the condition in a while loop. For example, you can use a comparison operator (<, <=, >, >=, ==, !=) to test a variable against a constant, or you can use a logical operator (&&, ||, not) to combine multiple conditions.

Here's an example of a while loop that reads input from the user until the user enters a blank line:

print "Enter some text (or a blank line to exit):\n";
while (my $line = <STDIN>) {
    chomp $line;
    if ($line eq '') {
        last; # exit the loop if the user entered a blank line
    }
    print "You entered: $line\n";
}

In this example, the while loop reads input from the user using the <STDIN> filehandle, which reads input from the standard input stream (usually the keyboard). The chomp function is used to remove the newline character from the end of the input. If the user enters a blank line, the last statement is used to exit the loop. Otherwise, the input is printed back to the user. The loop will continue to execute until the user enters a blank line.