Tinkering with Perl

Jonathan's Corner (Search & Sitemap) (Search & Sitemap) > Writing > Miscellaneous Nonfiction > Miscellaneous Nonfiction > Tinkering with Perl
Skip Back  Previous  38  39  40  41  42  43  44  45  46  47  Next  Skip Forward
Printer-Friendly Version

Foreach loops

One useful kind of loop, does something to each element of a list. For example, here is how might might code getting bundled up to go outside in the winter to go sledding:

@WinterClothing = ("coat", "snowpants", "boots", "gloves", "scarf", "hat");
foreach $ArticleOfClothing (@WinterClothing)
    {
    print "I'm putting on my $ArticleOfClothing.\n";
    }
Before dissecting exactly how this loop works, let me show you what it does. It prints out:

I'm putting on my coat.
I'm putting on my snowpants.
I'm putting on my boots.
I'm putting on my gloves.
I'm putting on my scarf.
I'm putting on my hat.
There are a couple of things going on here.

First, we assign a list.

Then we go through the loop several times -- each time, the variable $ArticleOfClothing is set to equal a different element of @WinterClothing, and the block of code is executed.

In that code, when Perl sees $ArticleOfClothing, it substitutes the value of $ArticleOfClothing (which may be "coat", "snowpants", etc.) for the name of the variable. So, the first time through, "I'm putting on my $ArticleOfClothing.\n" becomes "I'm putting on my coat.\n", where "\n" tells Perl that that's the end of the line.

Foreach loops should be used when you want to do something with every element of a list.

See also:

Statements - Lists - Flow control - Blocks - Loops - While loops - For loops

Tinkering with Perl is a free book that provides an introduction to programming in Perl, as well as a basic reference for things like foreach in Perl, if-then, and if-then-else, in addition to providing a glossary where you can find definitions for concatenate and other terms.

Tinkering with Perl may be one of the most popular offerings on this site, but it's not the only attraction. You can read a tongue-in-cheek Game Review: Meatspace, read an even more offbeat customer service survey (whether or not you actually fill it out), and spend a few minutes wishing your boss would read, The Administrator Who Cried, "Important!" (Not to mention that there are other things you can read here besides tech stuff, from Janra Ball: The Headache to The Spectacles.)

Read more...

Top

Skip Back  Previous  38  39  40  41  42  43  44  45  46  47  Next  Skip Forward
Printer-Friendly Version

JonathansCorner.com