if( condition ){
statements;
}else{
statements;
}
The else part is optional. The condition cab be any logical expression that evaluates to true or false.
These are two examples of if statements:
if( $#ARGV > -1 ){
print "The number of arguments is:", $#ARGV+1, "\n";
}
else{
print "No arguments\n";
}
...
if( $#ARGV == -1 ){
print "Please specify arguments\n";
exit 1;
}
unless( condition ){
statements;
}
If the condition is false the statements are executed. Thus, the following two examples are equivalent:
unless( $done ){
print "Keep on working ...\n";
}
if( not $done ){
print "Keep on working ...\n";
}
while( condition ){
statements;
}
The condition is tested, and if true, the statements are executed; then the condition is tested
again, and if true, the statements are executed; etc. The loop terminates when the condition is false.
The following example prints all fields of a hash variable:
%student = (
name => "Bob",
phone => "123-4567",
street => "Hal Greer Blvd, #1",
city => "Huntington",
state => "WV",
zip => 25755,
gpa => 3.75
);
@ks = keys(%student);
$i = 0;
while( $i <= $#ks ){
print "$ks[$i] = $student{$ks[$i]}\n";
$i++;
}
until( condition ){
statements;
}
The condition is tested, and if it's false, the statements are executed. Then the condition
is tested again, ....
for(initialization;condition;expression){
statements;
}
The initialization is executed before the loop and only once. Then the condition is tested, if it's true, the
statements are executed, then the expression is executed, and then the condition is tested again.
The loop stops when the condition is false. The following example prints all elements of an array:
@data = (1, 1, 2, 3, 5, 8, 13, 21, 34);
for($i=0;$i<=$#data;$i++){
print "$i: \t$data[$i]\n";
}
foreach scalar_variable (list){
statements;
}
The statements are executed for each item in the list; that is, we don't have to know how long the list is or
check whether the end has been reached. For example:
@data = (1, 1, 2, 3, 5, 8, 13, 21, 34);
foreach my $i (@data){
print "$i\n";
}
for my $i (1..10){
print "Hello!\n";
}
if( $#ARGV == -1 ){
die "You did not provide enough arguments";
}
can be written backward as:
die "You did not provide enough arguments" if $#ARGV == -1;Expression modifiers can be used only when the body of the construct is a simple statement. In the other words, the body cannot be an if or a while or any other multistatement body.
All the following examples are legal:
complain() unless $happy; sleep() while $tired && $there_is_time; cook() until $done;