perl foreach

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:

Perl hash introduction tutorial

Perl hash FAQ: Can you share some simple Perl hash examples?

Sure. If you're not familiar with them, a Perl hash is simply a Perl array that is indexed by a string instead of a number. A Perl hash is like a Map in the Java programming language, or an array in PHP.

Perl hash - Background information

To get started looking at a hash in Perl, let's look at a simple example. First, let's assume that Perl hashes don't exist. Next, lets assume that we need to store the prices of various food items you'll find in a restaurant.

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: