Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

10. More Control Structures > The for Control Structure

The for Control Structure

Perl’s for control structure is like the common for control structure you may have seen in other languages such as C. It looks like this:

for (initialization; test; increment) {
    body;
    body;
}

To Perl, though, this kind of loop is really a while loop in disguise, something like this:[266]

initialization;
while (test) {
    body;
    body;
    increment;
}

The most common use of the for loop, by far, is for making computed iterations:

for ($i = 1; $i <= 10; $i++) {  # count from 1 to 10
    print "I can count to $i!\n";
}

When you’ve seen these before, you’ll know what the first line is saying even before you read the comment. Before the loop starts, the control variable, $i, is set to 1. Then, the loop is really a while loop in disguise, looping while $i is less than or equal to 10. Between each iteration and the next is the increment, which here is a literal increment, adding one to the control variable, which is $i.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial