gpt4 book ai didi

match - perl6 语法 Action : unable to make anything if not using $/

转载 作者:行者123 更新时间:2023-12-04 14:55:51 24 4
gpt4 key购买 nike

我写了一个测试程序,现在看来如果不使用$/在一个
方法签名,因为我必须在方法内部使用 .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」

最佳答案

1) 如何make没有 $/make ...只是 $/.make(...) 的快捷方式.

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

2) 时间和原因 $/是只读的

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

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

您可以使用 is copy trait 覆盖正常的只读参数绑定(bind),并强制 $/成为例程中的可变项目容器:

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

这样,使用 .match例程内部会起作用,并且会存储一个新的 Match $/ 中的对象.但是您将无法访问原始 Match对象不再传递给例程,因此无法用 make 影响它.所以对于需要使用 .match的action方法,像你一样使用自定义参数名称是要走的路。

关于match - perl6 语法 Action : unable to make anything if not using $/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41027321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com