Doing Something with Every Element in a List
Problem
You want to repeat a procedure for every element in a list.
Often you use an array to collect information you’re interested in; for instance, login names of users who have exceeded their disk quota. When you finish collecting the information, you want to process it by doing something with every element in the array. In the disk quota example, you might send each user a stern mail message.
Solution
Use a foreach loop:
foreach $item (LIST) {
# do something with $item
}Discussion
Let’s say we’ve used @bad_users to
compile a list of users over their allotted disk quota. To call some
complain() subroutine for each one we’d use:
foreach $user (@bad_users) {
complain($user);
}Rarely is this recipe so simply applied. Instead, we often use functions to generate the list:
foreach $var (sort keys %ENV) {
print "$var=$ENV{$var}\n";
}Here we’re using sort and
keys to build a sorted list of environment
variable names. In situations where the list will be used more than
once, you’ll obviously keep it around by saving in an array.
But for one-shot processing, it’s often tidier to process the
list directly.
Not only can we add complexity to this formula by building up the
list in the foreach, we can also add complexity by
doing more work inside the code block. A common application of
foreach is to gather information on every element of a list, and then decide (based on that information) whether to do something. For instance, returning to the disk quota ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access