Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: List arguments of a method

by tobyink (Canon)
on May 15, 2014 at 08:43 UTC ( [id://1086117]=note: print w/replies, xml ) Need Help??


in reply to List arguments of a method

As others have said, no this can't be done. And certainly not via the symbol table because lexicals don't live there.

PadWalker provides a function called peek_sub which will tell you the names of lexical variables used within a sub. However, not all lexical variables necessarily correspond to parameters. The sub might contain, say, a foreach my $x (@array) loop where $x is just a loop variable; nothing to do with a function parameters.

A better alternative would be to write your module using one of the many CPAN extensions that provide declarative sugar for method signatures, and provide an introspection API. Here's an example using Kavorka:

use v5.14; package Module1 { use Moo; use Kavorka; method allVars (Int $no1, Int $no2, Str $name1, Str $name2) { say "all vars = $no1 $no2 $name1 $name2"; } } say "Let's check the method call works..."; my $obj = Module1->new; $obj->allVars(1, 2, "Foo", "Bar"); say "Now let's inspect its parameters..."; my $info = Kavorka->info(\&Module1::allVars); for my $parameter ($info->signature->positional_params) { say $parameter->name, " has type ", $parameter->type->name; }

The output is:

Let's check the method call works... all vars = 1 2 Foo Bar Now let's inspect its parameters... $no1 has type Int $no2 has type Int $name1 has type Str $name2 has type Str

Function::Parameters would similarly work. Method::Signatures would not because although it provides very similar declarative sugar, it doesn't seem to have an introspection API. MooseX::Method::Signatures would also work, but it's incredibly slow.

use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1086117]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (7)
As of 2024-04-24 07:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found