Can I use a standalone Signature as a signature in Perl 6?

寵の児 提交于 2019-12-22 03:48:40

问题


I was playing around with a Perl 6 implementation of a command-line program that takes several switches. The signature to MAIN was quite involved and a bit messy. I wondered if there was a way to define the signature somewhere else and tell the subroutine what to use:

# possibly big and messy signature
my $sig;
BEGIN { $sig = :( Int $n, Int $m ) };

multi MAIN ( $sig ) {
    put "Got $n and $m";
    }

MAIN doesn't see the variables in the signature even though the signature is set before MAIN compiles:

===SORRY!=== Error while compiling /Users/brian/Desktop/signature.p6
Variable '$n' is not declared
at /Users/brian/Desktop/signature.p6:7

I figured this sort of thing might be handy for generating methods after compile time and selecting signatures based on various factors.


回答1:


Short answer: No

Long answer: Still no. And if you could, you'd run into all kinds of trouble, because there's only one variable $n in your example. If you use the signature multiple times (or use it only once, and recurse into the subroutine that you attached it to), each signature binding would overwrite the previous value in that variable, causing some spooky action at a distance. There simply isn't a mechanism to cloning the variables involved in a free-floating signature.

Workarounds like using a match-all signature in the actual routine, and then use that to bind the capture to the signature suffer from this same flaw, and are thus IMHO not worth the trouble.

Maybe in the far future, some very advanced Macro feature might allow you to transplant signatures, but I don't think that part of macro development is even on our roadmap right now.

Instead of reusing bare signatures, you should reuse (possibly anonymous) routines with a signature attached, and install them with the name you want, for example

sub f(Int $n, Int $m) {
    # do something sensible here with $n and $m
}
constant &MAIN = &f;
# reuse &f for more 


来源:https://stackoverflow.com/questions/41531393/can-i-use-a-standalone-signature-as-a-signature-in-perl-6

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!