Perl Loops
Perl - Loops
Section titled “Perl - Loops”Loops are fundamental control structures in programming that allow you to execute a block of code repeatedly. Perl offers several types of loops to handle various iteration requirements.
It’s highly recommended to use use strict; and use warnings; at the beginning of your Perl scripts.
Perl Loop Types:
| Loop Type | Description |
|---|---|
while loop | Repeats a block of code as long as a given condition is true. The condition is tested before each iteration. |
until loop | Repeats a block of code as long as a given condition is false (i.e., until it becomes true). The condition is tested before each iteration. |
for loop (C-style) | A classic three-part loop (initialization; condition; increment/decrement) for controlled iteration. Often used for counting. |
foreach loop (or for list iterator) | Iterates over elements of a list (e.g., an array or a list literal). In each iteration, a loop variable takes the value of the current element. for and foreach are synonyms in this context. |
do...while loop | Similar to a while loop, but the condition is tested after each iteration. This guarantees the loop body executes at least once. |
do...until loop | Similar to an until loop, but the condition is tested after each iteration. Guarantees at least one execution. |
while Loop
Section titled “while Loop”Syntax:
while (condition) { # Code block to execute}Example:
#!/usr/bin/perluse strict;use warnings;
my $count = 1;while ($count <= 5) { print "Count is: $count\n"; $count++;}until Loop
Section titled “until Loop”Syntax:
until (condition) { # Code block to execute}Example:
#!/usr/bin/perluse strict;use warnings;
my $i = 10;until ($i < 5) { print "i is: $i\n"; $i--;}for Loop (C-style)
Section titled “for Loop (C-style)”Syntax:
for (my $variable = initial_value; condition; step) { # Code block to execute}Example:
#!/usr/bin/perluse strict;use warnings;
for (my $j = 0; $j < 3; $j++) { print "j is: $j\n";}foreach Loop (List Iterator)
Section titled “foreach Loop (List Iterator)”foreach (or its synonym for) iterates over a list of values. The loop variable is an alias to each element in the list, so modifying it modifies the element in the original list (if it’s an array).
Syntax:
foreach my $item (@list) { # Code block, $item is current element}
# Or using 'for' (identical behavior):for my $item (@list) { # Code block}
# If 'my $item' is omitted, $_ is used as the loop variable:# foreach (@list) {# print "Item: $_\n";# }Example:
#!/usr/bin/perluse strict;use warnings;
my @colors = qw(red green blue);foreach my $color (@colors) { print "Color: $color\n";}
# Modifying array elements (loop variable is an alias)my @numbers = (1, 2, 3);for my $num (@numbers) { $num *= 2; # Modifies the actual element in @numbers}print "Doubled numbers: @numbers\n"; # Output: 2 4 6do...while Loop
Section titled “do...while Loop”Syntax:
do { # Code block to execute} while (condition);Example:
#!/usr/bin/perluse strict;use warnings;
my $input;do { print "Enter 'quit' to exit: "; $input = <STDIN>; chomp $input; print "You entered: $input\n";} while ($input ne 'quit');do...until Loop
Section titled “do...until Loop”Syntax:
do { # Code block to execute} until (condition);Nested Loops
Section titled “Nested Loops”You can place one loop inside another. For example, iterating through a 2D structure (like a grid or matrix).
#!/usr/bin/perluse strict;use warnings;
for my $row (1..3) { for my $col ('A'..'C') { print "Cell: $row$col "; } print "\n"; # Newline after each row}Loop Control Statements
Section titled “Loop Control Statements”Perl provides statements to alter the flow of control within loops:
| Control Statement | Description |
|---|---|
next | Skips the rest of the current iteration and immediately starts the next iteration of the loop (similar to continue in C/Java). |
last | Immediately terminates the loop (similar to break in C/Java). |
redo | Restarts the current loop iteration from the beginning, without re-evaluating the loop condition or executing the continue block. |
continue BLOCK | A continue block, if present, is executed at the end of each loop iteration, just before the loop condition is re-evaluated (for while, until, C-style for). It’s not a standalone statement like next or last. |
Example using next and last:
#!/usr/bin/perluse strict;use warnings;
for my $num (1..10) { if ($num % 2 == 0) { next; # Skip even numbers } if ($num > 7) { last; # Exit loop if number is greater than 7 } print "Odd number: $num\n";}# Output: Odd number: 1, Odd number: 3, Odd number: 5, Odd number: 7Example of a continue block:
#!/usr/bin/perluse strict;use warnings;
my $lines_processed = 0;while (my $line = <DATA>) { chomp $line; next if $line =~ /^\s*$/; # Skip empty lines next if $line =~ /^#/; # Skip comment lines
print "Processing: $line\n"; # ... process $line ...}continue { $lines_processed++; # Executed for every iteration, even if 'next' was called}print "Total lines (including skipped): $lines_processed\n";
__DATA__# This is a commentData line 1
Data line 2The goto Statement
Section titled “The goto Statement”Perl supports a goto statement in various forms (goto LABEL, goto EXPR, goto &NAME). However, its use is generally discouraged in modern structured programming as it can make code harder to read and maintain. Loop control statements (next, last, redo) and well-structured subroutines are preferred alternatives.
Infinite Loops
Section titled “Infinite Loops”A loop becomes infinite if its condition never becomes false (for while/do...while) or never becomes true (for until/do...until).
# Infinite C-style for loop# for (;;) {# print "This loop runs forever...\n";# # Need a 'last' or external termination (Ctrl+C)# }
# Infinite while loop# while (1) {# print "So does this one...\n";# }Infinite loops must have a mechanism to exit, either via a last statement based on some internal condition, or by external interruption (e.g., Ctrl+C).