A Perl array and foreach example

Perl array foreach FAQ: How do I loop over every element in a Perl array with a for loop (or foreach loop)?

A friend recently asked how to create a simple array of numbers with Perl, and also how to iterate over that list of numbers in a Perl foreach loop. In this article I'll share with you the code I shared with him.

A Perl array and foreach loop example

In my sample code below I create a small Perl array named recs (or @recs, if you prefer) that contains the numbers 1 through 7. After creating the array I loop over the list of seven numbers using the Perl foreach operator, adding each number to a variable named $sum as I go along. After looping through each value in the array I print out the value of $sum (which happens to be 28).

With that introduction, here's my example Perl array/foreach code:

# create my perl array
@recs = qw/ 1 2 3 4 5 6 7 /;
$sum = 0;

# loop through the array using a perl foreach loop,
# calculating the sum of the numbers
foreach $rec (@recs)
  $sum = $sum + $rec;

# print the sum
print "sum = $sum\n";

As you might guess, the output from the Perl array and foreach loop looks like this:


Perl array and for loop example - Summary

While this is a fairly simple Perl for loop and array example, I hope it has been helpful. (Speaking for myself, when I don't use Perl very much I can never remember how to create a new Perl array, and I end up back here from time to time myself.)