您的位置:首页 > 其它

perl之更多的控制结构

2014-12-24 09:01 441 查看
1.unless/if结构

unless 条件为假的时候 才执行语句块。

eg:

unless($fred =~ /^[A-Z_]\w*$/i){

print "The value of \$fred doesn't look like a Perl indentifier name.\n";

}

想让于:

if(! ($fred =~ /^[A-Z-]\w*$/i)){

print "The value of \$fred doesn't look like a perl indentifier name.\n";

}

2.unless 's else statements

unless(condition)

{

statements;##run when condition false

}

else

{

statements;##run when condition true

}

3.until / while 控制结构 <===反置关系

until(condtion)

{

body; ###run when condition false

}

4.表达式修饰符用 if/unless while/until

statements if/unless/while/until

eg:

print "$n is a negative number.\n" if $n <0;

&error("Invalid input") unless &valid($input);

$i*2 until $i > $j;

print "",($n+=2) while $n < 10;

&greet($_) foreach @person;

print "fred is '$fred' , barney is '$barney'\n " if $I_am_curious;

5.裸块(naked)控制结构

所谓裸块(naked)就是指没有关键字或条件的快。

eg:

while(condition){

body;

body;

body;

}

去掉关键字和条件表达式:

{

body;

body;

body;

}

naked block 可以提供一个临时词法变量的作用域。

6.自递增与自递减

7.for 控制结构

for、 foreach 在perl中完全等价。

8.循环控制

1.last 相当于break

2.next 相当于continuous

3.redo 表示回到当前循环块的开头,但不测试任何条件表达式或进入下一个迭代。

last/next/redo都是对最内层循环块。

9.逻辑操作符(&& ||)

逻辑操作符有短路问题。但perl的逻辑操作符short-circuit逻辑操作符的值是最后被计算的部分,而不是一个布尔值。

10.三元操作符(?:)

11.使用部分计算操作符的控制结构

特点:对于&& 、|| 、?:有个共同属性即依赖于左侧值的真假,他们可能计算或不计算一个表达式。

eg:

($a > 10) || print "why is it not greater?\n";
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: