Subscribe to the RSS feed for the devdaily.com blog
Page not found (404 error) | alvinalexander.com

Page not found (404 error)

I’m sorry, the URL you are looking for can't be found.

This may be because I’ve made several significant changes to the website lately. If you want to take a few moments to search for the document you were looking for, you can try the Search Page here.

(I am trying to fix all the links I have broken, but it takes time.)

Thank you for your patience, and have a nice day!

Alvin Alexander
Owner, Editor, Link-breaker, Repairman,
AlvinAlexander.com


How do I do (fill in the blank) for each element in a Perl array?

Question: How do I do (fill in the blank) for each element in a Perl array?

Answer:

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.

Program output

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.

Good luck, and happy coding!

What's Related


devdaily logo