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;
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值