【问题标题】:perl6 grammar actions: unable to make anything if not using $/perl6 语法操作:如果不使用 $/ 则无法进行任何操作
【发布时间】:2017-04-22 23:29:05
【问题描述】:

我写了一个测试程序,现在看来如果我不使用$/在一个 方法签名,因为我必须在方法内部使用 .match,我不能再做任何事情。我做错了什么?

另一个问题是,如果.match 设置$/,并且$/ 是只读的,那么我不能在包含.match 语句的方法的签名中使用$/,我也不能方法中有多个.match,因为每个.match 都会尝试设置只读$/。这将是非常尴尬的编程。

这是一个测试程序,里面只有一个.match 语句和结果:

测试程序:

grammar test {
    regex TOP   { <foo><bar> }
    regex foo   { :i \s* foo \s* }
    regex bar   { :i \s  bar \s* }
}

class actTest {
    method foo ($x) {              # program fails if I use $/ in signature
      print "1 "; say $x;          # how to combine the 2 and show $x as match?
      print "2 "; say $x.WHAT;
      my $newStr = $x.Str;
      print "3 "; say $newStr;
      my $newMatch 
         = $newStr.match(/:i(f)(oo)/); # adverb cannot be outside?
      print "4 "; say $newMatch.WHAT;
      print "5 "; say $newMatch;
      print "6 "; say $/;
      my $oo = $newMatch[1].Str;
      print "10 "; say $oo;
      my $f = $newMatch[0].Str;
      print "11 "; say $f;
      my $result = $oo ~ $f;
      print "12 "; say $result;
      make $result;                # now I cannot make anything; huh???
    }
    method TOP ($/) { 
      print "8 "; say $<bar>;
      print "9 "; say $<foo>.made; # failed, method 'foo' makes nothing
      make $<bar> ~ $<foo>.made; 
    }
}

my $m = test.parse("Foo bar", actions => actTest.new);
print "7 "; say $m;

结果:

1 「Foo 」
2 (Match)
3 Foo 
4 (Match)
5 「Foo」
 0 => 「F」
 1 => 「oo」
6 「Foo」
 0 => 「F」
 1 => 「oo」
10 oo
 11 F
 12 ooF
1 「Foo」
2 (Match)
3 Foo
4 (Match)
5 「Foo」
 0 => 「F」
 1 => 「oo」
6 「Foo」
 0 => 「F」
 1 => 「oo」
10 oo
11 F
12 ooF
8 「 bar」
9 (Any)
Use of uninitialized value of type Any in string context.
Methods .^name, .perl, .gist, or .say can be used to stringify it to
something meaningful.
in method TOP at matchTest.pl line 28
7 「Foo bar」
 foo => 「Foo」
 bar => 「 bar」

【问题讨论】:

  • 这可能是一个错误,您不能使用.match( :i, /…/ ),或者您必须使用.match( rx :i /…/ )(如果是这种情况,如果您尝试前者应该会有警告)。

标签: match readonly signature assign raku


【解决方案1】:

1) 如何在没有$/ 的情况下使用make

make ... 只是$/.make(...) 的快捷方式。

如果您想影响与存储在$/ 中的对象不同的Match 对象,则必须直接使用方法形式,即在您的情况下为$x.make($result)

2) $/ 何时以及为何是只读的

默认情况下,$/ 绑定到一个普通的项目容器(如用my 声明的变量),即不是只读的。所以在一个例程中多次使用.match方法应该没有任何问题。

只有当您在例程签名中明确声明 $/ 作为参数时,$/ 才会直接绑定到传递给该例程的 Match 对象(未包装在项目容器中),因此将在例程中是只读的——因为这是正常签名绑定的工作方式。

您可以使用is copy trait 覆盖普通的只读参数绑定,并强制$/ 成为例程内的可变项容器:

method foo ($/ is copy) { ... }

这样,在例程中使用.match 将起作用,并将在$/ 中存储一个新的Match 对象。但是您将无法再访问传递给例程的原始Match 对象,因此无法使用make 影响它。因此,对于需要使用.match 的操作方法,使用您所做的自定义参数名称是可行的方法。

【讨论】:

    猜你喜欢
    • 2015-05-19
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 2013-03-31
    • 2014-02-17
    相关资源
    最近更新 更多