To 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:
if ( $password eq 'secret' ) { print "Come on in\n"; } else { print "Incorrect password\n"; }
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:
foreach my $thing (@my_room) { print "dusting $thing\n"; dust($thing); }
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:
foreach (@my_room) { print "dusting $_\n"; dust($_); }
Sometimes you need to continue looping while an event is happening, like reading input from standard input:
while ( my $line = <STDIN> ) { print "I got: $line"; }
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.
[124]STDIN is normally assumed here.
while (<>) { print "I got: $_"; }
Sometimes you need to interrupt the execute flow of your loop. Perl gives you three operators to do that (see Table 41-7).
Operator |
Example |
Description |
---|---|---|
while(<>){ next if $_ ne "continue\n"; } |
Jump to the top of the loop and iterate normally |
|
while(<>){ last if $_ eq "quit\n" } |
Jump out of the loop to the next line of the program |
|
for $url (@urls){ unless( $content = get($url) ){ print "couldn't fetch page - retrying\n"; redo; } } |
Jump to the top of the loop, but don't evaluate the loop condition |
Copyright © 2003 O'Reilly & Associates. All rights reserved.