Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

subroutine introspection

by misterb101 (Sexton)
on Dec 22, 2010 at 16:24 UTC ( #878584=perlquestion: print w/replies, xml ) Need Help??

misterb101 has asked for the wisdom of the Perl Monks concerning the following question:

Hi fellow Perl mates, I am working on a big application using ExtJS as a front-end. The interface communicates with the backend using Ext::Direct, a JSON API. What I am trying to do is create the API specification automatically. The API basically requires 2 things. specify which subroutines are made accessible and how many parameters they take, which I am solving like this:
sub foo($$) : Direct { ... }
The subroutine attribute is not a problem, but I can't seem to figure out how I can list how many arguments the subroutine requires:
my $numArgs = GiveMeTheNumberOfRequiredArgumentsOf(\&foo);
can anyone implement the 'GiveMeTheNumberOfRequiredArgumentsOf' subroutine for me ;) ? THANKS

Replies are listed 'Best First'.
Re: subroutine introspection
by JavaFan (Canon) on Dec 22, 2010 at 16:32 UTC
    You can get the prototype of a function as:
    prototype \&foo;
    I leave it up to you to parse the prototype (which has been enhanced in recent Perl versions).
      I have been programming Perl for 15 years... and I never knew this amazingly simple function.... Thanks for enlightening me :D
Re: subroutine introspection
by ikegami (Pope) on Dec 22, 2010 at 17:32 UTC

    Do you want the minimum number of arguments that must be specified, or the miminum number of arguments that must be passed to the function?

    # Minimum number of arguments that must be specified = 0 # Miminum number of arguments that must be passed = 1 sub f(_) {}
    # Minimum number of arguments that must be specified sub get_min_require_params { my ($sub) = @_; my $required_params = 0; my $prototype = prototype($sub); return 0 if !defined($prototype); for ($prototype) { if (/ \G (?: \$ | \* | \\(?: \[ [^\]] \] | [^\[] ) | \& ) /xsgc) { ++$required_params; next; } if (/ \G (?: \_ # Can only be followed by ";" | \@ | \% | \; | \z /xsgc) { last; } die("Unrecognized prototype\n"); } }

    To get the minimum number of arguments that must be passed to the function, you'll need to move "_" to the top "if".

    I don't see how either version is useful, so I'm sure there's an XY problem lurking.

    perlsub (for info on prototypes), prototype

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://878584]
Approved by Perlbotics
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2021-05-08 22:47 GMT
Find Nodes?
    Voting Booth?
    Perl 7 will be out ...

    Results (99 votes). Check out past polls.