13

在 Perl 5 和 Perl 6 的差异总结中,注意到该wantarray函数不见了:

wantarray() 不见了

wantarray 不见了。在 Perl 6 中,上下文向外流动,这意味着例程不知道它在哪个上下文中。

相反,您应该返回在每个上下文中都做正确事情的对象。

有人可以提供一个如何创建这样一个对象的例子吗?

4

2 回答 2

4

我认为2个例子可能是:


http://perlcabal.org/syn/S13.html#Type_Casting

一个类可以定义允许它像例程、数组或散列一样响应的方法。长格式如下:

method postcircumfix:<( )> ($capture) {...}
method postcircumfix:<[ ]> (**@slice) {...}
method postcircumfix:<{ }> (**@slice) {...}

这些有点笨拙,所以你也可以使用这些简短的形式:

method &.( $capture ) {...}
method @.[ **@slice ] {...}
method %.{ **@slice } {...}

Also, I think this might be relevant though less so: http://perlcabal.org/syn/S12.html

Search for:

You may write your own accessors to override any or all of the autogenerated ones.

So you return an object which has several context-specific accessors.


Interestingly enough, it started out with Perl6 replacing "wantarray" with a generic "want": RFC 98 (v1) context-based method overloading, circa 2000, also at http://dev.perl.org/perl6/rfc/21.html . I'm not sure why/when the change was made.

于 2010-10-18T20:59:38.623 回答
3

This comment on Reddit about the blog post Immutable Sigils and Context gives the following examples:

class GeoLocation is Array {
    method Str { 'middle of nowhere' }
}

sub remote_location {
    return GeoLocation.new(1e6 xx 3);
}

# or even easier:

sub remote_location {
    return (1e6 xx 3) but 'middle of nowhere';
}
于 2010-10-19T11:33:04.787 回答