【问题标题】:perl6 Need help to understand more about proto regex/token/ruleperl6 需要帮助以了解有关 proto regex/token/rule 的更多信息
【发布时间】:2017-07-06 14:32:38
【问题描述】:

以下代码取自 the Perl 6 documentation,在进行更多实验之前,我正在尝试更多地了解它:

proto token command {*}
      token command:sym<create>   { <sym> }
      token command:sym<retrieve> { <sym> }
      token command:sym<update>   { <sym> }
      token command:sym<delete>   { <sym> }
  1. 第一行中的* 是不是星号?可以是别的吗,比如

    proto token command { /give me an apple/ }
    
  2. “sym”可以是别的东西吗,比如

    command:eat<apple> { <eat> } ?
    

【问题讨论】:

    标签: regex raku proto


    【解决方案1】:

    {*} 告诉运行时调用正确的候选者。
    编译器允许您将其缩短为 {*}

    所有proto 例程都是这种情况,例如submethodregextokenrule

    regex proto 例程的情况下,只允许使用裸{*}
    主要原因可能是因为没有人真正想出一个好的方法来使它在正则表达式子语言中合理地工作。

    下面是一个proto sub 的示例,它执行了所有候选人共有的一些事情。

    #! /usr/bin/env perl6
    use v6.c;
    for @*ARGS { $_ = '--stdin' when '-' }
    
    # find out the number of bytes
    proto sub MAIN (|) {
      try {
        # {*} calls the correct multi
        # then we get the number of elems from its result
        # and try to say it
        say {*}.elems #            <-------------
      }
      # if {*} returns a Failure note the error message to $*ERR
      or note $!.message;
    }
    
    #| the number of bytes on the clipboard
    multi sub MAIN () {
      xclip
    }
    
    #| the number of bytes in a file
    multi sub MAIN ( Str $filename ){
      $filename.IO.slurp(:!chomp,:bin)
    }
    
    #| the number of bytes from stdin
    multi sub MAIN ( Bool :stdin($)! ){
      $*IN.slurp-rest(:bin)
    }
    
    sub xclip () {
      run( «xclip -o», :out )
      .out.slurp-rest( :bin, :close );
    }
    

    【讨论】:

      【解决方案2】:

      这回答了您的第二个问题。是的,已经很晚了。 你必须区分两个不同的syms(或eats)。将令牌定义为“副词”(或扩展语法标识符,无论您想如何称呼它)的那个,以及令牌本身上的那个。

      如果您在令牌正文中使用&lt;eat&gt;,Perl 6 将根本找不到它。你会得到一个类似的错误

      No such method 'eat' for invocant of type 'Foo'
      

      Foo 是语法的名称。 &lt;sym&gt; is a predefined token,匹配token中副词(或配对值)的值。

      原则上,您可以使用扩展语法来定义多标记(或规则或正则表达式)。但是,如果你尝试用这种方式定义它,你会得到一个不同的错误:

      Can only use <sym> token in a proto regex
      

      所以,你的第二个问题的答案是否定的。

      【讨论】:

      • 非常感谢 jjmerelo 的帮助!!
      猜你喜欢
      • 2014-08-04
      • 1970-01-01
      • 2023-03-28
      • 2018-09-06
      • 2014-10-31
      • 2010-11-07
      • 2019-04-11
      • 2017-06-19
      • 2016-05-03
      相关资源
      最近更新 更多