perl学习(8) 控制:unless,until,next,redo,last
Perl中实现了所有C 的操作符! Perl力求代码最少!? 1.1.unlessunless的含义是:除非条件为真,否则执行块中的代码,和if正好相反 unless($fred=~ /^[A-Z_]w*$/i){ ?????? print “The value of $fred doesn’t looklike a Perl identifier name.n”; } else { ?????? print “match successn”; } #大写字母或者下划线开头的字符串 ? 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.forfor($i=1; $i <=10; $i++){ #从1到10 ?????? print “I can count to $i;n”; } ? 对于Perl 解析器(parser)而言,关键字foreach 和for 是等价的。 ?????? print “I can count to $_!n”; }? 1.5.lastlast 会立刻结束循环。(这同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 "test1n"; ???last; ???print "test2"; }? 1.6.nextnext 之后,又会进入下一轮循环(这和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.nn"; $errors++; redo; #跳转到循环顶端 } } print "You’ve completed the test,with $errorserrorn"; 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”; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |