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/perluse 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;}总结
以上是内存溢出为你收集整理的perl given与C switch的区别全部内容,希望文章能够帮你解决perl given与C switch的区别所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)