perl while

Perl loop examples - The Perl foreach, for, while, and until loops

Perl loop FAQ: Can you share some "Perl loop" examples (Perl for loops, foreach loops, and Perl arrays)?

I've written a variety of "Perl loop" stories before, but I've never shown all the different Perl loop operators in one place before. In this Perl tutorial I'll try to provide a summary of the different Perl loop constructs.

A simple Perl array

Before showing any Perl loop examples, we'll need an array to work with. Here's a simple Perl array that contains five strings:

The Perl until loop examples and syntax

Perl until loop FAQ: Can you share some examples of the Perl until loop syntax?

The Perl until loop is similar to the Perl while loop, but essentially does the opposite thing. Where the Perl while operator will run this loop forever:

while ('true')
{
  # do stuff here
}

the Perl until loop will never run this loop:

Perl hash foreach and while - How to loop over a hash in Perl

Perl hash question: How do I traverse the elements of a hash in Perl?

Answer: There are at least two ways to loop over all the elements in a Perl hash. You can use either (a) a Perl foreach loop, or (b) a Perl while loop with the each function. I find the Perl foreach syntax easier to remember, but the solution with the while loop and the each function is preferred for larger hashes.

A Perl hash print example (printing hash elements)

Perl hash question: How do I print the elements stored in a hash in Perl?

Answer: There are at least two ways to print the elements of a Perl hash, including one way that I think is easy to remember, and another way that is recommended if you have a very large hash.

Perl hash printing with a foreach loop

The easier way for me to remember is with a Perl foreach loop. In the following sample code I'll first create a Perl hash, and then I'll print out each key and value stored in the hash: