Home » Perl Array with Loops

Perl Array with Loops

by Online Tutorials Library

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.

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.

Output:

10  20  30  40  50  

Perl Array with while Loop

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

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.

Output:

John  John  John  John  John  

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

You may also like