41.6. Perl Boot Camp, Part 3: Branching and LoopingTo do any interesting stuff with data, Perl needs to be able to branch and loop. Perl supports the C-like if-then-else construct, as the following shows:
You can also invert simple tests that only have one statement in the then block. print "Don't I know you?\n" if $user eq 'joe'; You can invert the logic of if by using unless: print "Please supply command line arguments\n" unless @ARGV; The print happens only if @ARGV is empty. Sometimes you need to iterate through each element of a list. This can be done with the foreach loop:
A synonym for foreach is for. Bourne shell hackers (or those who don't like typing) may feel more comfortable using for rather than then foreach. Each time through the loop, $thing is aliased to the next element in @my_room. Any change to $thing will change that element in the array, so be careful. If you don't supply a scalar variable like $thing, Perl will set $_ for you each time through the loop. The previous example could also be written:
Sometimes you need to continue looping while an event is happening, like reading input from standard input:
Each line of input a user provides is stored in $line, including the newline at the end. When the user hits the end-of-file control key (CTRL-D), the loop exits. Like the foreach loop, you can leave off the scalar variable while reading from a filehandle,[124] and $_ will be set to the next line of input each time through the loop.
Sometimes you need to interrupt the execute flow of your loop. Perl gives you three operators to do that (see Table 41-7). Table 41-7. Loop flow-control operators
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|