http://www.perlmonks.org?node_id=878584

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
--
Cheers,
Rob

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
      --
      Cheers,
      Rob
Re: subroutine introspection
by ikegami (Patriarch) 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