perl学习---控制:unless,until,next,redo,last

1.1.unless

unless 的含义是:除非条件为真,否则执行块中的代码,和if正好相反

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

print “The value of \$fred doesn’t looklike a Perl identifier name.\n”;

}

else

{

print “match success\n”;

}

# 大写字母或者下划线开头的字符串

1.2.until

将 while 循环的条件部分取反

until($j> $i){

$j *=2;

}

1.3.表达式修饰符

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

&error(“Invalidinput”) unless &valid($input);

$i *=2 unitl $i > $j;

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

&greet($_)foreach @person;

Perler 一般都喜欢少输入些字符。简写的形式读起来很像英文:输出这段消息,如果 $n 小于 0 。

条件表达式虽然被放在后面,也是先被求值

1.4.for

for($i=1; $i <=10; $i++){ # 从1到10

print “I can count to $i;\n”;

}

对于Perl 解析器(parser)而言,关键字 foreach 和 for 是等价的。

for(1..10){ # 实际上是 foreach 循环 , 从1到10

print “I can count to $_!\n”;

}

1.5.last

last 会立刻结束循环。(这同C 语言或其它语言中的“ break ”语句类似)。

# 输出所有出现 fred 的行,直到遇见 _ _END_ _ 标记

while(<STDIN>){

if(/_ _ END_ _/){

# 这个标记之后不会有其它输入了

last;

}elsif(/fred/){

print;

}

}

##last 跳转到这里 ##

Perl 的5 种循环体分别是 for , foreach , while , until ,以及“裸”块{}, last 对整个循环块其作用。

#! /usr/bin/perl -w

use strict;

use warnings ;

{

print "test1\n";

last;

print "test2";

}

1.6.next

next 之后,又会进入下一轮循环(这和C 或者类似语言的“ continue ”相似)

1.7.redo

循环控制的第三个操作是 redo 。它会调到当前循环块的顶端,不进行条件表达式判断以及接着本次循环。(在C 或类似语言中没有这种操作。)

#!/usr/bin/perl -w

use strict ;

use warnings;

#输入测试

my @words = qw{ fredbarney pebbles dinoWilma betty };

my $errors = 0;

​foreach(@words)

{    ##redo 跳到这里##

print "Type the word $_: ";

chomp(my $try = <STDIN>);

if($try ne $_){

print "sorry ?That’s not right.\n\n";

$errors++;

redo; #跳转到循环顶端

 }
}
print "You’ve completed the test, with $errorserror\n";

1.8.标签块

Larry 推荐标签均大写。这会防止标签和其它标识符冲突,同时也使之在代码中更突出。同时,标签很少使用,通常只在很少一部分程序中出现。

这个和c是同样的,为了保证逻辑和维护的简明,尽量不适用goto

goto

1.9.逻辑操作符

逻辑与 AND ( && )

逻辑或 OR ( || )

逻辑或||有另外的含义,perl里面成为:短路操作

my$last_name = $last_name{$someone} ||‘(No last name)’

即在 %last_name 中不存在 $someone 时, $last_name = ‘(No last name)’

逻辑操作符还能用来控制结构

($m< $n) && ($m = $n);

($m> 10) || print“why it it not greater?\n”

1.10. 三元操作符

my$location = &is_weekend($day) ? “home”: “work”;