Questions about this topic? Sign up to ask in the talk tab.

Perl/Basics/Loops

From NetSec
(Redirected from Perl loops)
Jump to: navigation, search

A loop is a block of code that continues to execute until a condition is met.

While

  • A while loop executes while a condition is true.
my $switch;
my $counter;
while (undef $switch) {
    print $counter;
    $counter++;
    $switch = 1 if ($counter > 100);
}
 The above code will execute until $switch is defined.

It is possible to create an infinite loop using while (1) { ... }.

Until

  • An until loop executes until a condition is true.
my $switch;
my $counter;
until (defined $switch) {
    print $counter;
    $counter++;
    $switch = 1 if ($counter > 100);
}
 The above code will execute until $switch is defined.

For

  • A for loop has a built-in counter and stops at a pre-defined number.
my @messages = ("Hello world!\n","I like perl!\n");
for (my $counter = 0; $counter < $#array; ++$counter) {
   print $messages[$counter];
}
 The above code will iterate through every element in an array.

It is possible to create an infinite loop using for (;;) {...}.

Foreach

  • A foreach loop is built specifically for array handling and iterates through all of the elements in an array.
my @messages = ("Hello world!\n","I like perl!\n");
foreach my $message (@messages) {
   print $message;
}
 The above code will iterate through every element in an array.