Perl Array with Loops

Perl array elements can be accessed within a loop. Diferent types of loops can be used.

We will show array accessing with following loops:

  • foreach loop
  • for loop
  • while loop
  • until loop

Perl Array with foreach Loop

In foreach loop, the control variable is set over the elements of an array. Here, we have specified $i as the control variable and print it.

snippet
@num = qw(10 20 30 40 50);
foreach $i (@num) {
  print "$i\n";
}

Output:

Output
10 20 30 40 50

Perl Array with for Loop

A control variable will be passed in for loop as the index of the given array.

snippet
@num = qw(10 20 30 40 50);
for($i = 0; $i < 5; $i++){
  print "@num[$i]\n";
}

Output:

Output
10 20 30 40 50

Perl Array with while Loop

The while loop executes as long as the condition is true.

snippet
$i = 5;
while ($i > 0) {
  print "$i\n";
  $i--;
}

Output:

Output
5 4 3 2 1

Perl Array with until Loop

The until loop works like while loop, but they are opposite of each other. A while loop runs as long as a condition is true whereas an until loop runs as long as condition is false. Once the condition is false until loop terminates.

The until loop can be written on the right hand side of the equation as an expression modifier.

snippet
@your_name = "John";
print "@your_name\n" until $i++ > 4;

Output:

Output
John John John John John

In the above program, once $i is greater than 4 according to the condition, loop iteration stops.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents