Any.match 是做什么的?

What does Any.match do?

它具有看似简单的代码:

 method match(Any:U: |) { self.Str; nqp::getlexcaller('$/') = Nil }

但是,这是它的行为:

(^3).match(1) # OUTPUT: «「1」␤»

到目前为止,还不错。

say (1,3 ... * ).match(77); # OUTPUT: «Nil␤»

太棒了。现在发生了什么?

say (1,3 ... * ).match(1);    # OUTPUT: «Nil␤»
say (1,3 ... * ).match(/\d/); # OUTPUT: «Nil␤»

不喜欢序列。

say (^10).match(/\d/); # OUTPUT: «「0」␤»

好的,又说得通了。

say <a b c>.match(/\w/); # OUTPUT: «「a」␤»

恢复正常。那么是不是不喜欢Seqs呢?我假设,因为我查看了其他 类' 代码并且 match 没有重新实现,所以它们都在调用该代码。但是我看不出如何从 NPQ 返回一个字符串并设置一个变量,或者为什么它对序列不起作用。

.match是大海捞针一串。无限序列字符串化为 '...'.

say (1,3 ... 9).Str;        # 1 3 5 7 9
say (1,3 ... 9).match: '1'; # 「1」

say (1,3 ... *).Str;        # ...
say (1,3 ... *).match: '.'; # 「.」

我是如何解决这个问题的

首先,您正在查看错误的方法定义:

method match(Any:U: |) { ... }

Any:U 有点像 Any $ where not .defined 除非它匹配你会收到错误消息 "Parameter '<anon>' of routine 'match' must be a type object of type 'Any', not an object instance ...".

但是您传递的是 定义的 Seq。因此,您的 .match 调用不会分派到您正在查看的方法定义。

要找出方法分派的目标,请使用:

say (1,3 ... *).^lookup('match').package ; # (Cool)

A defined Seq 将因此分派到 the Cool code:

method match(Cool:D: |c) {
    ...
    self.Stringy.match(|c)
}

那么,下一个:

say (1,3 ... *).^lookup('Stringy').package ; # (Mu)

the code

multi method Stringy(Mu:D $:) { self.Str }

所以检查:

say (1,3 ... *).Str; # ...

宾果。

并确认:

say (1,3 ... *).match: '.'; # 「.」

接受的答案完美地解释了发生了什么。我只是添加这个来展示一些例子,说明如何做 OP 似乎想要做的事情。

doug$ perl6
To exit type 'exit' or '^D'
> say (^3).any.match(/\d/)
any(「0」, 「1」, 「2」)
> say (^3).any.match(/\d/).so
True
> say (^3).any.match(/ <alpha> /).so
False
> say ('a'..'c').any.match(/ <alpha> /).so
True
> # say (0 ... *).any.match(/ \d /).so ## ==> never terminates
Nil
> say (0 ... *).first(/ \d /)
0
> say (0 ... *).first(/ \d\d /)
10
>