In a while loop, the block of code between the { and } braces is executed so long as the conditional expression is true. Think of it as saying, "Execute while this condition remains true." Here's an example:
while (@ARGV) {
print "ARG: $ARGV[0] \n";
shift @ARGV;
}
This trivial example prints the value of each argument passed to the shell script. Translated to English, the while condition says to continue so long as the input argument string is not null. You might think that this loop would continue to print the first argument $ARGV[0] forever and ever, since you don't expect the value of the @ARGV variable (the list of arguments from the command line) to change during the course of running the script. You'd be right, except that I slipped the shift command into the body of the loop.
What shift does is discard the first argument and reassign all the $ARG variables--so the new $ARGV[0] gets the value that used to be in $ARGV[1] and so on. Accordingly, the value in @ARGV gets shorter and shorter each time through the loop, and when it finally becomes null, the loop is done.
The until Statement
The until construct works almost exactly the same as while. The only difference is that until executes the body of the loop so long as the conditional expression is false, whereas while executes the body of the loop so long as the conditional expression is true. Think of it as saying, "Execute until this condition becomes true."
Let's code the previous example using an until loop this time and making it a little fancier by adding a counter variable:
$count=1;
until ( ! @ARGV ) {
print "Argument number $count : $ARGV[0] \n";
shift;
$count++;
}
The only new concept here is the strange-looking line that increments the counter. The $count++ syntax is equivalent to $count=$count+1, but the former is more common in Perl and C language programming. You can also decrement a value using the $count-- syntax.
The foreach Statement
The foreach statement provides yet another way to implement a loop in a Perl script. The general form of the for construct is shown here:
foreach $item ( in-some-array )
{
do something with $item
}
Each time through the loop, the value of the $item variable is assigned to the next item in the array. When you've processed all the items in the array, the loop is done. Here's an example similar to the until and while loops you saw earlier in this section:
foreach $var (@ARGV)
{
print "NEXT ARG: $var \n";
}
Previous Lesson: Perl Logic
Next Lesson: Perl and Files
Comments - most recent first
|
|
||