如何在运行时获取子例程的签名? [英] How do I get the signature of a subroutine in runtime?

查看:39
本文介绍了如何在运行时获取子例程的签名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Perl 通过 CORE::prototype 提供了一个 API,允许您获得原型.Sub::Util 进一步记录了这一点,这是用于处理 subs 的记录方法,

Perl provides an API via CORE::prototype, that allows you to get a prototype. This is further documented by Sub::Util which is the documented method for working with subs,

Sub::Util::prototype,

返回给定 $code 引用的原型,如果有的话,作为字符串.这与 CORE::prototype 操作符相同;将其包含在这里只是为了与其他函数的对称性和完整性.

Returns the prototype of the given $code reference, if it has one, as a string. This is the same as the CORE::prototype operator; it is included here simply for symmetry and completeness with the other functions.

但是,我没有看到任何关于如何获取签名的信息在运行时?perl 是否提供此功能?

However, I don't see anything anywhere on how to get the signatures in runtime? Does perl make this available?

推荐答案

这是非常...间接的,但是解析子并解析签名代码.

This is very ... indirect, but deparse the sub and parse the signature code.

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";
}

这篇关于如何在运行时获取子例程的签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆