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

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.

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

Array with for Loop

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

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

Array with while Loop

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

Example
snippet
$i = 5;
while ($i > 0) {
  print "$i\n";
  $i--;
}
Output
5 4 3 2 1

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.

Example
snippet
@your_name = "John";
print "@your_name\n" until $i++ > 4;
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 +