相关文章推荐

unless ($fred =~ /^([A-Z_]\w*$/i) {
print "The value of \$fred doesn't look like a Perl identifier name. \n";
}

使用unless意味着,要么条件为真,要么执行某块代码。这就好像使用if控制结构来判断相反的条件。另一种说法是它类似于独立的else子句。也就是说,当看不懂某个unless语句时,可以用如下的if语句来代替:

if ($fred =~ /^([A-Z_]\w*$/i) {
//什么都不做
} else {
print "The value of \$fred doesn't look like a Perl identifier name. \n";
}

如此操作与运行效率高低无关,两种写法应该会被统译成相同的内部字节码。另外一个改写的方法,就是以取反操作符!来否定条件:

if ( ! ($fred =~ /^([A-Z_]\w*$/i) ) {
print "The value of \$fred doesn't look like a Perl identifier name. \n";
}

unless附带的else子句

其实哪怕是在unless结构中也可以使用else语句,虽然支持这样的语法,但是可能会导致困惑:

#!/usr/bin/perl -w
unless ($mon =~ /^Feb/) {
print "This month has at least thirty days.\n";
} lese {
print "Do you see what's going on here?\n";
}
#如果用if语句我们可以写成这样:
if ($mon =~ /^Feb/) {
print "Do you see what's going on here?\n";
} else {
print "This month has at least thirty days.\n";
}

 
推荐文章