Skip to content

Perl Loops

while Loop

Basic while Loop

perl
my $count = 0;

while ($count < 5) {
    print "Count: $count\n";
    $count++;
}

Using while to Read Files

perl
open(my $fh, '<', 'file.txt') or die "Cannot open file: $!";

while (my $line = <$fh>) {
    chomp $line;
    print "$line\n";
}

close($fh);

Infinite Loop

perl
my $count = 0;

while (1) {
    print "Count: $count\n";
    $count++;
    last if $count >= 5;  # Use last to exit
}

until Loop

until is shorthand for while not, continues loop while condition is false.

Basic until Loop

perl
my $count = 0;

until ($count >= 5) {
    print "Count: $count\n";
    $count++;
}

Using until to Wait for Condition

perl
my $ready = 0;

until ($ready) {
    print "Not ready yet, waiting...\n";
    sleep 1;
    $ready = 1;  # Simulate condition becoming true
}

print "Ready!\n";

for Loop

Basic for Loop

perl
for (my $i = 0; $i < 5; $i++) {
    print "i = $i\n";
}

C-style for Loop

perl
for (my $i = 10; $i > 0; $i--) {
    print "Countdown: $i\n";
}

Multiple Initialization and Iteration

perl
for (my $i = 0, my $j = 10; $i < 10 && $j > 0; $i++, $j--) {
    print "i=$i, j=$j\n";
}

Omitting Parts

perl
# Omit initialization
my $i = 0;
for (; $i < 5; $i++) {
    print "i = $i\n";
}

# Omit condition (infinite loop)
for (my $i = 0; ; $i++) {
    print "i = $i\n";
    last if $i >= 5;
}

# Omit iteration
for (my $i = 0; $i < 5;) {
    print "i = $i\n";
    $i++;
}

foreach Loop

Basic foreach Loop

perl
my @fruits = ("apple", "banana", "orange");

foreach my $fruit (@fruits) {
    print "Fruit: $fruit\n";
}

Simplified Form (using $_)

perl
my @numbers = (1, 2, 3, 4, 5);

foreach (@numbers) {
    print "Number: $_\n";
}

Modifying Array Elements

perl
my @numbers = (1, 2, 3, 4, 5);

foreach my $num (@numbers) {
    $num *= 2;  # Modifications reflect in array
}

print "@numbers\n";  # 2 4 6 8 10

Iterating Over Hashes

perl
my %person = (name => "Alice", age => 25, city => "New York");

# Iterate over keys
foreach my $key (keys %person) {
    print "$key: $person{$key}\n";
}

# Iterate over key-value pairs
while (my ($key, $value) = each %person) {
    print "$key: $value\n";
}

Loop Control

last - Exit Loop

perl
for (my $i = 0; $i < 10; $i++) {
    print "i = $i\n";
    last if $i == 5;  # Exit loop
}

next - Skip Current Iteration

perl
for (my $i = 0; $i < 10; $i++) {
    next if $i % 2 == 0;  # Skip even numbers
    print "Odd number: $i\n";
}

redo - Restart Current Iteration

perl
for (my $i = 0; $i < 5; $i++) {
    print "Start of iteration $i\n";
    
    if ($i == 2) {
        $i--;  # Decrement to restart
        redo;
    }
    
    print "End of iteration $i\n";
}

Labels and Nested Loops

perl
OUTER: for (my $i = 0; $i < 5; $i++) {
    INNER: for (my $j = 0; $j < 5; $j++) {
        print "i=$i, j=$j\n";
        last OUTER if $i == 2 && $j == 2;  # Exit outer loop
        last INNER if $j == 2;  # Exit inner loop
    }
}

do-while and do-until

do-while Loop

perl
my $count = 0;

do {
    print "Count: $count\n";
    $count++;
} while ($count < 5);

do-until Loop

perl
my $count = 0;

do {
    print "Count: $count\n";
    $count++;
} until ($count >= 5);

Ensure Execution at Least Once

perl
my $number;

do {
    print "Enter positive number: ";
    chomp($number = <STDIN>);
} while ($number <= 0);

print "You entered: $number\n";

map and grep

map - Transform List

perl
my @numbers = (1, 2, 3, 4, 5);

# Multiply each element by 2
my @doubled = map { $_ * 2 } @numbers;
print "@doubled\n";  # 2 4 6 8 10

# Convert to uppercase
my @words = qw(hello world perl);
my @upper = map { uc } @words;
print "@upper\n";  # HELLO WORLD PERL

# Create key-value pairs
my @fruits = qw(apple banana orange);
my %prices = map { $_ => rand(10) } @fruits;

grep - Filter List

perl
my @numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

# Get even numbers
my @evens = grep { $_ % 2 == 0 } @numbers;
print "@evens\n";  # 2 4 6 8 10

# Get numbers greater than 5
my @greater_than_five = grep { $_ > 5 } @numbers;
print "@greater_than_five\n";  # 6 7 8 9 10

# Filter using regular expression
my @words = qw(apple banana orange grape);
my @with_a = grep { /a/ } @words;
print "@with_a\n";  # apple banana orange grape

Combining map and grep

perl
# Filter then transform
my @numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
my @evens_doubled = map { $_ * 2 } grep { $_ % 2 == 0 } @numbers;
print "@evens_doubled\n";  # 4 8 12 16 20

# Transform then filter
my @squared_even = grep { $_ % 2 == 0 } map { $_ ** 2 } (1..10);
print "@squared_even\n";  # 4 16 36 64 100

Loop Scalars

Reading Multiple Lines of Input

perl
print "Enter text (Ctrl+D to end):\n";

while (my $line = <STDIN>) {
    chomp $line;
    print "You entered: $line\n";
}

Using <> to Read Files

perl
# Read files from command line arguments
while (my $line = <>) {
    chomp $line;
    print "$line\n";
}

Reading File into Array

perl
open(my $fh, '<', 'file.txt') or die "Cannot open file: $!";

# Read all lines into array
my @lines = <$fh>;
close($fh);

# Process each line
foreach my $line (@lines) {
    chomp $line;
    print "$line\n";
}

Practice Examples

Example 1: Multiplication Table

perl
#!/usr/bin/perl
use strict;
use warnings;

for (my $i = 1; $i <= 9; $i++) {
    for (my $j = 1; $j <= $i; $j++) {
        printf "%dx%d=%-3d", $j, $i, $i * $j;
    }
    print "\n";
}

Example 2: Finding Prime Numbers

perl
#!/usr/bin/perl
use strict;
use warnings;

print "Enter upper limit: ";
chomp(my $limit = <STDIN>);

print "Prime numbers: ";
for (my $n = 2; $n <= $limit; $n++) {
    my $is_prime = 1;
    
    for (my $i = 2; $i * $i <= $n; $i++) {
        if ($n % $i == 0) {
            $is_prime = 0;
            last;
        }
    }
    
    print "$n " if $is_prime;
}
print "\n";

Example 3: Fibonacci Sequence

perl
#!/usr/bin/perl
use strict;
use warnings;

print "Enter number of terms: ";
chomp(my $n = <STDIN>);

my @fib = (0, 1);

for (my $i = 2; $i < $n; $i++) {
    $fib[$i] = $fib[$i-1] + $fib[$i-2];
}

print "First $n terms of Fibonacci sequence: @fib\n";

Example 4: File Processing

perl
#!/usr/bin/perl
use strict;
use warnings;

my $file = "data.txt";

open(my $fh, '<', $file) or die "Cannot open $file: $!";

my $line_count = 0;
my $word_count = 0;
my $char_count = 0;

while (my $line = <$fh>) {
    chomp $line;
    $line_count++;
    $char_count += length($line);
    
    my @words = split /\s+/, $line;
    $word_count += scalar @words;
}

close($fh);

print "Statistics:\n";
print "Lines: $line_count\n";
print "Words: $word_count\n";
print "Characters: $char_count\n";

Example 5: Password Guessing

perl
#!/usr/bin/perl
use strict;
use warnings;

my $correct_password = "secret";
my $attempts = 0;
my $max_attempts = 3;

while ($attempts < $max_attempts) {
    print "Enter password: ";
    chomp(my $password = <STDIN>);
    
    if ($password eq $correct_password) {
        print "Password correct!\n";
        last;
    } else {
        $attempts++;
        my $remaining = $max_attempts - $attempts;
        
        if ($remaining > 0) {
            print "Incorrect password, $remaining attempts remaining\n";
        } else {
            print "Incorrect password, attempts exhausted\n";
        }
    }
}

Summary

In this chapter, we learned Perl loops:

  1. ✅ while loops
  2. ✅ until loops
  3. ✅ for loops
  4. ✅ foreach loops
  5. ✅ Loop control (last, next, redo)
  6. ✅ do-while and do-until
  7. ✅ map and grep
  8. ✅ File reading loops

Next, we will learn Perl Subroutines (Functions).

Content is for learning and research only.