加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

在Perl 5中获取开关/案例行为

发布时间:2020-12-15 21:24:29 所属栏目:大数据 来源:网络整理
导读:是否有一个整洁的方法在Perl 5中做case或switch语句?在我看来,他们应该包括一个开关版本6 .. 我需要这个控制结构在一个脚本,我听说你可以导入一个“交换模块”。但是如何实现它,而无需导入以最小化依赖和获得可移植性? 解决方法 如果你使用的Perl 5.10
是否有一个整洁的方法在Perl 5中做case或switch语句?在我看来,他们应该包括一个开关版本6 ..

我需要这个控制结构在一个脚本,我听说你可以导入一个“交换模块”。但是如何实现它,而无需导入以最小化依赖和获得可移植性?

解决方法

如果你使用的Perl 5.10你有 given/when这是一个switch语句(注意,它可以做比比较regexes,阅读链接的文档,以查看其全部潜力):
#or any of the dozen other ways to tell 5.10 to use its new features
use feature qw/switch/; 

given($string) {
    when (/^abc/) { $abc     = 1; }
    when (/^def/) { $def     = 1; }
    when (/^xyz/) { $xyz     = 1; }
    default       { $nothing = 1; }
}

如果你使用Perl 5.8或更早版本,你必须使用if / elsif / else语句:

if    ($string =~ /^abc/) { $abc     = 1; }
elsif ($string =~ /^def/) { $def     = 1; }
elsif ($string =~ /^zyz/) { $xyz     = 1; }
else                      { $nothing = 1; }

或嵌套condition operators (?:):

$string =~ /^abc/ ? $abc     = 1  :
$string =~ /^def/ ? $def     = 1  :
$string =~ /^xyz/ ? $xyz     = 1  :
                    $nothing = 1;

在Core Perl(Switch)中有一个模块,通过source filters为你提供假的switch语句,但是我的理解是它是fragile:

use Switch;

switch ($string) {
    case /^abc/ {
    case /^abc/ { $abc     = 1 }
    case /^def/ { $def     = 1 }
    case /^xyz/ { $xyz     = 1 } 
    else        { $nothing = 1 }
}

或替代语法

use Switch 'Perl6';

given ($string) {  
    when /^abc/ { $abc     = 1; }
    when /^def/ { $def     = 1; }
    when /^xyz/ { $xyz     = 1; }
    default     { $nothing = 1; }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读