Perl Tutorial

Fundamentals

Input and Output

Control Flow

Arrays and Lists

Hash

Scalars

Strings

Object Oriented Programming in Perl

Subroutines

Regular Expressions

File Handling

Context Sensitivity

CGI Programming

Misc

Loops in Perl

Looping is a fundamental concept in programming, allowing for the repetition of a block of code as long as a condition is met. Perl offers several loop constructs, each with its unique advantages. In this tutorial, we'll explore these constructs.

1. The for Loop

The for loop in Perl is similar to other programming languages. It allows you to execute a block of code a specific number of times.

for (my $i = 0; $i < 5; $i++) {
    print "$i\n";  # Prints numbers 0 to 4
}

2. The foreach Loop

The foreach loop is used to iterate over a list of items.

my @fruits = ('apple', 'banana', 'cherry');
foreach my $fruit (@fruits) {
    print "$fruit\n";
}

You can also use for as a synonym for foreach:

for my $fruit (@fruits) {
    print "$fruit\n";
}

3. The while Loop

The while loop continues executing as long as the condition remains true.

my $i = 0;
while ($i < 5) {
    print "$i\n";  # Prints numbers 0 to 4
    $i++;
}

4. The until Loop

The until loop is the opposite of while. It continues executing as long as the condition remains false.

my $i = 0;
until ($i >= 5) {
    print "$i\n";  # Prints numbers 0 to 4
    $i++;
}

5. Loop Controls

Perl provides several keywords to control loop execution:

  • next: This is akin to continue in some languages. It skips the current iteration and continues with the next one.

    for my $i (1..5) {
        next if $i == 3;
        print "$i\n";  # Prints 1, 2, 4, 5
    }
    
  • last: This is similar to break in some languages. It exits the loop immediately.

    for my $i (1..5) {
        last if $i == 3;
        print "$i\n";  # Prints 1, 2
    }
    
  • redo: Repeats the current iteration of the loop. The loop condition is not evaluated again, which means redo can create an infinite loop if not used carefully.

    my $i = 0;
    while ($i < 3) {
        print "$i\n";  # Infinite loop unless incremented somewhere
        redo if some_condition();  # Replace some_condition() with actual condition
        $i++;
    }
    

6. Loop Labels

Labels can be used in conjunction with loop controls. They're especially handy when working with nested loops.

OUTER: for my $i (1..3) {
    INNER: for my $j (1..3) {
        if ($j == 2) {
            next OUTER;
        }
        print "($i, $j)\n";
    }
}

7. The C-style for Loop

Besides the regular for loop, Perl supports a C-style for loop.

for ($i = 0, $j = 5; $i < 5; $i++, $j--) {
    print "($i, $j)\n";
}

Conclusion

Loops are a vital component of programming in Perl. Understanding the different loop constructs and controls available ensures you can iterate and control the flow of your program effectively. As always, the Perl documentation (perldoc perlsyn) provides in-depth details on these constructs.

  1. Types of loops in Perl:

    • Description: Perl supports various types of loops, including foreach, while, and for.
    • Example Code:
      foreach my $item (@items) {
          # Loop body
      }
      
      while ($condition) {
          # Loop body
      }
      
      for (my $i = 0; $i < 5; $i++) {
          # Loop body
      }
      
  2. Using foreach loop in Perl:

    • Description: The foreach loop iterates over elements of a list or array.
    • Example Code:
      my @colors = ('red', 'green', 'blue');
      
      foreach my $color (@colors) {
          print "$color ";
      }
      
  3. Perl while loop examples:

    • Description: The while loop repeats as long as a specified condition is true.
    • Example Code:
      my $count = 0;
      
      while ($count < 5) {
          print "$count ";
          $count++;
      }
      
  4. Nested loops in Perl:

    • Description: Perl allows nesting loops, where one loop is inside another.
    • Example Code:
      for my $i (1..3) {
          for my $j (1..2) {
              print "$i,$j ";
          }
      }
      
  5. Perl loop control statements:

    • Description: Loop control statements like last, next, and redo provide additional control within loops.
    • Example Code:
      foreach my $number (1..10) {
          last if $number > 5;
          next if $number % 2 == 0;
          print "$number ";
      }
      
  6. Looping through arrays in Perl:

    • Description: Arrays can be iterated using foreach or for loops.
    • Example Code:
      my @numbers = (1, 2, 3, 4, 5);
      
      foreach my $num (@numbers) {
          print "$num ";
      }
      
  7. Iterating over hash values in Perl:

    • Description: Hashes can be iterated using foreach to access values.
    • Example Code:
      my %person = ('name' => 'John', 'age' => 30, 'city' => 'New York');
      
      foreach my $value (values %person) {
          print "$value ";
      }
      
  8. Perl loop labels and next statement:

    • Description: Loop labels and the next statement allow controlling the flow in nested loops.
    • Example Code:
      OUTER: for my $i (1..3) {
          INNER: for my $j (1..2) {
              next OUTER if $i + $j > 3;
              print "$i,$j ";
          }
      }
      
  9. Infinite loops in Perl and how to break them:

    • Description: Infinite loops can be created using constructs like while (1). Break them using last.
    • Example Code:
      my $counter = 0;
      
      while (1) {
          last if $counter > 5;
          print "$counter ";
          $counter++;
      }