第十章 其他控制结构
unless: 和if相反。条件为假时,执行后面语句。
unless () {
}
unless也可附带else,但通常情况我们会使用if else。
------------------------------------------------
until: 和while相反,条件为假时,执行循环。
until () {
}
------------------------------------------------
条件修饰词
print "$n is a negative number \n" if $n < 0;
相当于
if ($n < 0) {
print "$n is a negative number \n";
}
类似的还有:
&error("Invalid input") unless &valid($input);
$i *=2 until $i > $j;
------------------------------------------------
裸块控制结构
{
xxx
}
可以用来为临时变量圈定有效范围。
------------------------------------------------
elsif子句:
if () {
}elsif () {
}else {
}
------------------------------------------------
自增和自减
$bedrock = 42;
$bedrock++;
my @people = qw/fred barney fred wilma dino barney fred pebbles/;
my %count;
$count{$_}++ foreach @people;
while ( ($key,$value) = each %count){
print "$key => $value\n";
}
这个程序走遍整个序列,记录下每个单词出现的次数。非常快速简易。
中间的 $count{$_}++ foreach @people;
相当于
foreach (@people) {
if ($count{$_}) {
$count{$_}++;
}else {
$count{$_} = 1;
}
}
相当于
foreach (@people) {
$count{$_}++;
}
------------------------------------------------
自增的值
my $m = 5;
my $n = ++$m; #m=6,n=6;
my $c = --$m; #m=5,c=5
my $d = $m++; #m=6,d=5
my $e = $m--; #m=5,e=6
------------------------------------------------
for控制结构
for (init; test; increment) {
body;
}
相当于while循环:
init;
while (test) {
body;
increment;
}
------------------------------------------------
foreach和for的秘密关系:
其实foreach和for是等价的,通常纯正的foreach是更好的选择。
------------------------------------------------
循环控制:
last操作符:相当于break,跳出循环
while () {
if (/__END__/) {
last;
} elsif (/fred/) {
print;
}
}
next:结束当前迭代,相当于continue
last和next都只对最内层的循环快发挥作用。perl中有5中循环块:for,
foreach, while, until, 裸块。
redo将控制返回到本次循环的顶端。next是正常进行下一次迭代,而redo则是
重新执行这次迭代。
------------------------------------------------
带标签的块:通常大写,标识一个程序代码块
LINE: while (<>) {
foreach (split) {
last LINE if /__END__/;
...
}
}
------------------------------------------------
三目操作符
条件表达式?真表达式:假表达式
在三层嵌套时,可简洁:
my $size =
($width < 10) ? "small" :
($width < 20) ? "medium" :
($width < 50) ? "large" :
"extra-large";
------------------------------------------------
逻辑操作符:
逻辑与&&
逻辑或||
这种短路逻辑操作符,返回的值是表达式的值。
my $last_name = $last_name{$someone} || '(No last name)';
打开文件的习惯写法:
open CHAPTER, $filename
or die "Can't open '$filename': $!";
习题:猜数字游戏
$num = int(1 + rand 100);
print "Please guess the value from 1 to 100\n";
while (<>) {
chomp;
if ($num == $_) {
print "Correct\n";
last;
} elsif ($_ > $num) {
print "Too high\n";
next;
} else {
print "Too low\n";
next;
}
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/11903161/viewspace-689285/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/11903161/viewspace-689285/