Perl get list of desired parameters

Is there an agreement to request a list of necessary parameters for a function? I would like to be able to call a routine that will tell me that I need to provide $ phrase and $ times when calling @repeat.

use strict; use warnings; sub repeat { my $phrase = shift; my $times = shift; return $phrase x $times; } 
+5
source share
3 answers

You seem to be asking for introspection . There are many OO frameworks that provide it (e.g. Moose ). But, if you want to be able to declare a function and then examine it from your program, Function :: Parameters is the smart way.

From Function :: Parameters :: Info Summary:

  use Function::Parameters; fun foo($x, $y, :$hello, :$world = undef) {} my $info = Function::Parameters::info \&foo; my $p0 = $info->invocant; # undef my @p1 = $info->positional_required; # ('$x', '$y') my @p2 = $info->positional_optional; # () my @p3 = $info->named_required; # ('$hello') my @p4 = $info->named_optional; # ('$world') my $p5 = $info->slurpy; # undef my $min = $info->args_min; # 4 my $max = $info->args_max; # inf my $invocant = Function::Parameters::info(method () { 42 })->invocant; # '$self' my $slurpy = Function::Parameters::info(fun {})->slurpy; # '@_' 

The introspection function in the :: Info module is actually implemented using Moose.

+4
source

Of course, you can create some kind of control mechanism yourself, depending on your needs. But there are some modules that will help you sign subroutines. I will offer 3 of them:

+6
source

In my opinion, the best solution to this is to use Perl6::Parameters , which, as its name implies, emulates the semantics of Perl 6 without the horror of using a source filter.

+2
source

Source: https://habr.com/ru/post/1213641/


All Articles