Perl Programming Page 2 - Perl 101 (Part 3) - Looping The Loop |
The most basic loop available in Perl is the "while" loop, and it lookslike this: Or, to make the concept clearer, The "condition" here is a standard Perl conditional expression, whichevaluates to either true or false. So, were we to write the above examplein Perl, it would look like this: How about an example you could actually use in your real-life job? Well,here's one - be warned, however, that it's primarily meant for managers whowork in the Dilbert Zone. And here's what it looks like: Let's take a closer look at this code. The first part of the program shouldbe familiar to you by now - we're simply asking for input, assigning it toa variable, and then using the chomp() function to remove the trailingcarriage return. At this point, we begin checking the value of the variable - *while* thisvalue is *not equal* to "y", or an affirmative reply, we continue printingthe question over and over again, and stop only when the value becomesequal to "y". At this point, the lines following the loop are executed, andthe appropriate output displayed. The end result? A company full of "satisfied" employees [whoever says Perlisn't powerful should take a look at that HR manager's Christmas bonus...] Here's another example, this one using a "while" loop and a conditionalexpression that contains a number instead of a string: In case you flunked math class, the factorial of a number X is the productof all the numbers between 1 and X. And here's what the output looks like: And if you have a calculator handy, you'll see that 7*6*5*4*3*2*1 = 5040 Once the user enters a number, a "while" loop is used to calculate theproduct of that number and the scalar variable $factorial [initialized to1] - this value is stored in the variable $factorial. Next, the number isreduced by 1, and the process is repeated, until the number becomes equalto 1. At this stage, the value of $factorial is printed. This article copyright Melonfire 2000. All rights reserved.
blog comments powered by Disqus |