#!/usr/bin/perl -w use Switch; use Getopt::Long; my $val = 'a'; GetOptions( 'val=s' => \$val ); switch($val){ case 'a' {print $val} case 'b' {print ("val = b")} case 1 {print ("val = 1")} case m/ab/ {print ("val is match \"abc\". ")} else {print "wrong input.\n"} }
结果:
zl@zl-vm:~/study/perl/switch$
zl@zl-vm:~/study/perl/switch$ perl switch.pl -val=b
val = b
zl@zl-vm:~/study/perl/switch$ perl switch.pl -val=abc
val is match "abc".
zl@zl-vm:~/study/perl/switch$
总结:
1,可以向c语言那样来使用case语句,非常方便。
2,还可以使用正则表达式来进行判断。
3,最后一个使用else来进行结尾。
参考:http://search.cpan.org/~chorny/Switch-2.17/Switch.pm
use Switch; switch ($val) { case 1 { print "number 1" } 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" } case (\%hash) { print "entry in hash" } case (\&sub) { print "arg to subroutine" } else { print "previous case not true" } }