Perl array and foreach - How to operate on each Perl array element

Perl array/foreach FAQ: How do I perform an operation on each element in a Perl array? (Also written as, How do I use the Perl foreach operator, or What is the Perl foreach syntax?)

Software developers are always working with arrays. In Perl, that means that you're working with (a) normal Perl arrays or (b) Perl hashes (called 'associative arrays' before Perl 5.x).

When it comes to working with a regular Perl array (not a hash), here's a simple technique I often use to loop through the array, and perform an operation on each Perl array element:

#!/usr/bin/perl -w

@homeRunHitters = ('McGwire', 'Sosa', 'Maris', 'Ruth');

foreach (@homeRunHitters) {
  print "$_ hit a lot of home runs in one year\n";

In this example, homeRunHitters is a simple Perl array (i.e., it's just an array indexed by number; hashes are arrays indexed by strings). Here, I use the Perl foreach  statement to cycle through the elements in the array. The special variable $_ holds the value of the element being processed during each cycle in the Perl foreach loop.

Output from this Perl array printing program looks like this:

McGwire hit a lot of home runs in one year
Sosa hit a lot of home runs in one year
Maris hit a lot of home runs in one year
Ruth hit a lot of home runs in one year

If you're interested in using this technique when tackling your Perl arrays, all you have is put your logic inside of the Perl foreach loop.