【问题标题】:Proper perl switch formatting in emacsemacs 中正确的 perl 开关格式
【发布时间】:2009-10-28 22:08:33
【问题描述】:

编辑:阅读回复后,我认为答案是“不要这样做”,因此我将适当的回复标记为官方答案。

有没有一种简单的方法可以让 emacs 显示 perl 切换语句,例如 perldoc.perl.org 的 switch page

这是 perldoc.perl.org 上的格式:

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" }
}

这是在 sn-p 上运行M-x indent-regioncperl-mode 中的格式:

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" }
    }

我莫名其妙地想坚持使用 if-elsif 结构......

ps。我认为this 描述了所需的过程,但看起来需要一段时间才能解析。

【问题讨论】:

    标签: perl emacs indentation switch-statement


    【解决方案1】:

    抱歉,我无法在 emacs 方面为您提供帮助。但是,我会建议你坚持使用

    if ( condition ) {
    
    }
    elsif( other_condition ) {
    
    }
    else {
    
    }
    

    而不是使用可怕的Switch.pm。见Nicholas Clark's message to perl5.porters

    Switch 将在下一个主要版本中从 Perl 核心发行版中删除。

    更多讨论请关注PerlMonks

    正如 Randal Schwartz 在下面的评论中指出的那样,从 5.10 版开始,Perl 有一个强大的replacement,它不依赖于源过滤器:

    use feature "switch";
    
    given($_) {
       when (/^abc/) { $abc = 1; }
       when (/^def/) { $def = 1; }
       when (/^xyz/) { $xyz = 1; }
       default { $nothing = 1; }
    }
    

    【讨论】:

    • Switch.pm 正在被删除,因为它已按照给定/何时进行了本地化。因此,您对删除 Switch 的评论很好,但是您将其替换为给定/何时,而不是 Perl4 构造。 :)
    • @Randal 够公平的。但是我在早期版本中对Switch.pm 感到头疼,如果有人不使用 5.10,最好避免使用它,恕我直言。
    • 感谢您的提醒!我绝对不知道 Switch.pm 的给定/时间或问题。这也为我节省了很多可能很糟糕的重构时间/精力。
    • 值得注意的是,cperl-mode 解析给定/何时构造比 StackOverflow 解析器好得多;)
    • cperl-mode 6.2 格式给定/何时以与 switch/case 相同的方式,并且也不将它们突出显示为关键字。我猜那在待办事项清单上,那么!
    【解决方案2】:

    您是否考虑过使用调度表,正如 Mark Jason Dominus 在Higher-Order Perl? 中概述的那样

    【讨论】:

    • 不,我没有。谢谢你提供的详情。我绝对可以看到调度表的使用,但考虑到这个问题,这有点离题。
    【解决方案3】:

    如果 cperl 的格式不正确,请尝试 perltidy。

    这是一个在当前区域的 Emacs 中运行 perltidy 的简洁函数:

    ;;灵活的功能来运行 perltidy (defun perltidy-region () “在当前区域运行 perltidy。” (交互的) (保存游览 (shell-command-on-region (point) (mark) "perltidy -q" nil t)))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 2010-10-14
      • 1970-01-01
      相关资源
      最近更新 更多