条件语句
Perl的if语句和C++的if语句几乎一样,但是Perl支持一种比较特殊的unless条件语句,和if语句的逻辑处理正好相反,if是如果条件满足就执行body,unless是条件buma不满足就执行body。unless语句后面也可以跟可选的else语句,也可以后跟elsif再加一个else语句。
此外,Perl也支持C++风格的三目运算符:Exp1 ? Exp2 : Exp3;
#!/usr/bin/perl
$bVar = "true";
unless("$bVar" != "true") {
print "bVar equal true\n";
} else {
print "bVar not equal true\n";
}
$result = (10 > 20)?"true":"false";
print "$result\n";
[root@izuf682lz6444cynn96up0z basic]# ./control.pl
bVar equal true
false
注意:数字0、字符串'0'、""、空list()、和undef为false,其他value均为true。
循环语句
Perl除了支持C++风格的while循环、for循环和do...while循环(包括continue语句),还支持until循环和foreach循环。
until循环
until循环重复执行语句,直到给定的条件为true。循环主题执行之前会先测试条件。
eg:
#!/usr/bin/perl
$a = 0;
until($a == 10){
print "$a\n";
$a = $a + 2;
}
[root@izuf682lz6444cynn96up0z basic]# ./until.pl
0
2
4
6
8
foreach循环
foreach循环用于迭代列表或者集合变量的值。
eg:
#!/usr/bin/perl -w
@array = ('google', 'baidu', 'alibaba');
foreach(@array){
print "$_\t";
}
print "\n";
foreach $e (@array){
print "$e\t";
}
print "\n";
foreach(a..d, A..D){
print "$_\t";
}
print "\n";
[root@izuf682lz6444cynn96up0z basic]# ./foreach.pl
Unquoted string "a" may clash with future reserved word at ./foreach.pl line 13.
Unquoted string "d" may clash with future reserved word at ./foreach.pl line 13.
google baidu alibaba
google baidu alibaba
a b c d A B C D
循环控制语句
next语句:停止执行从next语句的下一句开始到循环体结束标识符之间的语句,转去执行continue语句块,然后再返回到循环体的起始处开始执行下一次循环。
last语句:退出循环语句块,从而结束循环,类似于C++中的break语句。
continue语句。
redo语句:redo语句直接转到循环体的第一行开始重复执行本次循环,redo语句之后的语句不再执行,continue语句块也不再执行。
goto语句。