Perl 通过 CORE::prototype
提供 API ,这样你就可以得到一个原型(prototype)。 Sub::Util
进一步记录了这一点这是使用潜艇的记录方法,
Sub::Util::prototype
,
Returns the prototype of the given
$code
reference, if it has one, as a string. This is the same as theCORE::prototype
operator; it is included here simply for symmetry and completeness with the other functions.
但是,我没有看到任何关于如何获得 signatures 的信息。在运行时? perl 是否提供此功能?
最佳答案
这是非常...间接的,但是解析子并解析签名代码。
sub foo ($bar) { return 0 }
use B::Deparse;
$foo = B::Deparse->new->coderef2text(\&foo);
# contents of foo:
# BEGIN {${^WARNING_BITS} = "\x10\x01\x00\x00\x00\x50\x04\x00\x00\x00\x00\x00\x00\x55\x50\x55\x50\x51\x01"}
# use feature 'signatures';
# die sprintf("Too many arguments for subroutine at %s line %d.\n", (caller)[1, 2]) unless @_ <= 1;
# die sprintf("Too few arguments for subroutine at %s line %d.\n", (caller)[1, 2]) unless @_ >= 1;
# my $bar = $_[0];
# return 0;
@foo = split /\n/, $foo;
if ($foo[2] =~ /use feature 'signatures'/ &&
$foo[3] =~ /Too many arguments/ &&
$foo[4] =~ /Too few arguments/) {
@sig = ();
$n = 5;
do {
($sig) = $foo[$n] =~ /my (\W\w+) = /;
push @sig,$sig if $sig;
$n++;
} while ($sig);
print "Signature is (", join(",",@sig), ")\n";
}
关于perl - 如何在运行时获取子程序的签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63836449/