Perl foreach/array example code

By Alvin J. Alexander, devdaily.com

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 foreach loop. In this quick blog post I'll share with you the code I shared with him.

In my sample code below I create a Perl array named recs (or @recs, if you prefer) that contains the numbers 1 through 7. After creating the array I iterate over the list of seven numbers using Perl's 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 sample Perl array/foreach code:

@recs = qw/ 1 2 3 4 5 6 7 /;
$sum = 0;
foreach $rec (@recs)
{
  $sum = $sum + $rec;
}

print "sum = $sum\n";

As usual, feel free to use this sample code in your own applications.


devdaily logo