Questions about this topic? Sign up to ask in the talk tab.
Difference between revisions of "Perl/Basics/Loops"
From NetSec
AlizaLorenzo (Talk | contribs) (Created page with "A loop is a block of code that continues to execute until a condition is met.") |
Chantal21I (Talk | contribs) |
||
Line 1: | Line 1: | ||
A loop is a block of code that continues to execute until a condition is met. | A loop is a block of code that continues to execute until a condition is met. | ||
+ | |||
+ | ===While=== | ||
+ | {{:Perl/Basics/Loops/While}} | ||
+ | ===Until=== | ||
+ | {{:Perl/Basics/Loops/Until}} | ||
+ | ===For=== | ||
+ | {{:Perl/Basics/Loops/For}} | ||
+ | ===Foreach=== | ||
+ | {{:Perl/Basics/Loops/For Each}} |
Latest revision as of 01:34, 19 July 2012
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.