perl given与C switch的区别
发布时间:2020-12-16 00:24:47 所属栏目:大数据 来源:网络整理
导读:perl 中 "use v5.10"后即可使用given-when语法,和C的switch类似。 但是有一个比较重要的区别,given的when每次continue到下一个when的时候还会判断下一个when的条件是否为真,而C 中的switch一旦某个case分支没有break的话,下一个case的条件跳过判断。所以
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 : $filen"; 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 heren"); } return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |