switch语句是这样工作的:让多个数值和一个测试值相比较,而执行与测试值相匹配的值,如果任意一个存在的话,执行对应代码。
Perl中没有内建的switch语句,你不得不使用长梯状的if、elsif和else语句进行多重检测。但你可以自己做一个:或者使用Switch模块;或者使用代码块,因为块非常像只执行一次的循环,实际上可以使用诸如last这样的循环控制语句离开这个块。
1.使用Switch模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #!/usr/bin/perl use strict; use Switch; my $val = "haha"; my %hash = ( "haha" => "weibiao" ); my @array; switch ($val) { #是不是和数字相等 case 1 { print "number 1" } #是否 eq "a"是不是和字符串a相等 case "a" { print "string a" } #是否在这个[]匿名的数组里面(也可以理解为列表) case [ 1 .. 10, 42 ] { print "number in list" } #是否在数组中,其实和上面是一样的 case ( @array ) { print "number in list" } #是否是字母 case /w+/ { print "pattern" } case qr/w+/ { print "pattern" } #查找HASH中有无$val这个键值 case ( %hash ) { print "entry in hash" } #这里的意思是把$val传给函数做参数 case ( &ha ) { print "arg to subroutine" } #未找到对应的值,相当于c里面的default咯,就这么简单 else { print "previous case not true"; } } ##子函数## sub ha { $_ = shift; print "$_ n"; } |
2.自己构建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #!/usr/bin/perl -w use strict; my $message; print "Enter command: "; while () { SWITCH: { /^run$/ && do { $message = "Runningn"; last SWITCH; }; /^stop$/ && do { $message = "Stoppedn"; last SWITCH; }; /^connect$/ && do { $message = "Connectedn"; last SWITCH; }; /^find$/ && do { $message = "Foundn"; last SWITCH; }; /^q$/ && do { exit; }; DEFAULT: $message = "No match.n"; } print $message; print "Enter command: "; } |
3.一个实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #!/usr/bin/perl -w use strict; sub useage() { print "用法:$0 1|2|3|4 r|s|rsn"; } sub jboss_oprate() { my ( $host, $oprate ) = @_; system( "ssh", "$host", ". /etc/profile;$oprate" ); } print "本程序用于重启rs1 rs2 rs3 rs4中的jboss服务器n"; useage(), exit if $#ARGV != 1; my $host = shift; my $oprate = shift; SWITCH: { $host == 1 and $host = "rs1", last; $host == 2 and $host = "rs2", last; $host == 3 and $host = "rs3", last; $host == 4 and $host = "rs4", last; useage(), exit; } SWITCH: { $oprate eq "r" and $oprate = "jbr", last; $oprate eq "s" and $oprate = "jbs", last; $oprate eq "rs" and $oprate = "jbrestart", last; useage(), exit; } print "现在对服务器$host进行$oprate操作:n"; &jboss_oprate( $host, $oprate ); print "程序运行完毕n"; |