How do I do <fill-in-the-blank> for each element in an array?

By Alvin J. Alexander, devdaily.com

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

When it comes to 'normal arrays', we're often asked the question "How do I do <fill-in-the-blank> for each element in an array"? Here's a simple technique we often use:

#!/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 array (i.e., it's just an array indexed by number; hashes are arrays indexed by strings). Here, we use the foreach statement to cycle through the elements in the array. The special variable $_ holds the value of the element being processed during each loop in the foreach statement.

Output from this 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 arrays, all you have is put your logic inside of the foreach loop.


devdaily logo