关于perl中如何实现switch结构

来源:互联网 发布:java gui 程序设计pdf 编辑:程序博客网 时间:2024/04/29 10:13

众所周知,perl中没有内置的switch结构,但是switch确实很有用,它提供了一个简单明了的结构体,可以避免烦琐的if  else。既然perl不支持switch结构,我们可以自己写一个switch结构。我的switch结构如下:

print("Enter command:");
while(<>)
{
    SWITCH:{
           /run/ && do{
               print("match:".$_."/n");
               last SWITCH;
           };

           /q/ && do{
               print("match:".$_."/n");
               exit;
           };

    DEFAULT:        $message = "No match:$_/n";
                    print($message."/n");
    }

    print("Enter command:");
}

实现机制很简单,就是添加一个SWITCH标签,在SWITCH中以模式匹配的方式来实现case语句。

last SWITCH是退出当前SWITCH语句块儿。

 

Sylvester

youhaodeyi@gmail.com

原创粉丝点击