perl given与C switch的区别

perl 中 "use v5.10"后即可使用given-when语法,和C的switch类似。

但是有一个比较重要的区别,given的when每次continue到下一个when的时候还会判断下一个when的条件是否为真,而C 中的switch一旦某个case分支没有break的话,下一个case的条件跳过判断。所以 《learning perl》中那道用given-when语法可以替换多个if分支来做文件可读,可写,可执行的判断。如果是C的switch的话,则无法做这种替换。

参看以下两种代码:

#!/bin/perl

use v5.10;
use warnings;
use strict;

chomp(my $file = <STDIN>);
die "File $file not exist" if not -e file;

given($file) {
	print "FILE : $file\n";
	when (-r $file) { print "can read"; continue } 
	when (-w $file) { print "can write"; continue }		#被continue时也会判断条件 -w是否成立
	when (-x $file) { print "can run" }
	default { print "Default" }
	print "\n";
}

#include <stdio.h>

int main(int argc, char **argv)
{
	int number = 1;
	
	switch (number) {
		case 1:
			printf("1 here.\n");
		case 2:
			printf("2 here.\n");	#没有break时,并不会再做2的判断,而是直接执行。
		case 3:
			printf("3 here.\n");
		default:
			printf("default here\n");
	}
	
	return 0;
}



猜你喜欢

转载自blog.csdn.net/irwin_chen/article/details/7521577