Perl array elements can be accessed within a loop. Diferent types of loops can be used.
We will show array accessing with following loops:
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.
@num = qw(10 20 30 40 50); foreach $i (@num) { print "$i\n"; }
A control variable will be passed in for loop as the index of the given array.
@num = qw(10 20 30 40 50); for($i = 0; $i < 5; $i++){ print "@num[$i]\n"; }
The while loop executes as long as the condition is true.
$i = 5; while ($i > 0) { print "$i\n"; $i--; }
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.
@your_name = "John"; print "@your_name\n" until $i++ > 4;
In the above program, once $i is greater than 4 according to the condition, loop iteration stops.