Control structures
- if/then/elsif/else
- Results of an if
must be a brace-enclosed block, unlike C.
- unless is the
opposite of if
- while
- do {} while
- do {} until
- for()
for() in C-style
- Standard C-style "for ( start_expression; test_expression;
loop_expression )"
for ( my $i = 0; $i < 10; $i++ ) {
print "$i squared is ", $i*$i, "\n";
}
- Not used very often because the list-handling functions handle this
better
foreach() as a
loop over a list
- Iterates over the contents of a list, assigning it to a variable.
my @people = qw( Tom Dick Harry );
foreach my $person ( @people ) {
print "Here's a person: $person\n";
}
- Modifying the loop variable modifies the value in the list.
# Double prices across the board
my @prices = ( 1.99, 4.99, 7.99 );
foreach my $price ( @prices ) {
$price = $price * 2;
}
# @prices is now ( 3.98, 9.98, 15.98 )
- If the variable isn't specified, special variable $_ is used.
Errors & warnings
- die "message" stops
immediately with "message" sent to stderr.
- warn "message" sends
"message" sent to stderr and continues.
- if die or warn 's message doesn't end
with "\n", Perl automatically appends line information, as in:
my $length = -1;
die "Invalid length" if ($length < 0);
# prints "Invalid length at line 47"
|
|
|