DEV Community

kobaken
kobaken

Posted on

Released Sub::Meta that handles function meta information in Perl 5

Sub::Meta - handle subroutine meta information - metacpan.org

Sub::Meta is a module to handle meta information such as subroutine names and subroutine input/output.
There are similar modules such as Sub::Identify,Sub::Util and Sub::Info, but writeSub::Meta because it can not handle the meta information of the input/output of the subroutine.

The basic usage is as follows.
You can get meta information based on the code reference:

use Sub::Meta;

sub hello($) :mehtod { }
my $meta = Sub::Meta->new(sub => \&hello);
$meta->subname;     # hello
$meta->sub;         # \&hello
$meta->subname;     # hello
$meta->fullname;    # main::hello
$meta->stashname;   # main
$meta->file;        # path/to/file.pl
$meta->line;        # 5
$meta->is_constant; # !!0
$meta->prototype;   # $
$meta->attribute;   # ['method']
Enter fullscreen mode Exit fullscreen mode

You can also handle meta information without passing a code reference:

my $meta = Sub::Meta->new(subname => 'foo');
$meta->subname; # foo
Enter fullscreen mode Exit fullscreen mode

Function input/output meta information can be added:

# INPUT
my $parameters = Sub::Meta::Parameters->new(
  args => [
    { name => '$a', type => 'Int' },
    { name => '$b', type => 'Int'},
  ],
  nshift => 1,
);

$meta->set_parameters($paramters);
$meta->parameters->args;
# [
# Sub::Meta::Param->new({ name => '$a', type => 'Int' }),
# Sub::Meta::Param->new({ name => '$b', type => 'Int' })
# ]

# OUTPUT
my $returns = Sub::Meta::Returns->new(
  scalar => 'Int',
  list   => 'Int',
);
$meta->set_returns($returns);
$meta->returns->scalar; # 'Int'

Enter fullscreen mode Exit fullscreen mode

Let's dig into the motivations for working with function input and output meta information.

Perl5 has many modules that validate function input, such as Params::Validate,Data::Validator, Smart::Args,Function::Parameters, Type::Params, etc.

Each module has different usability, I thought it was somewhat stressful.
Also, I wanted to do Static analysis because I was annotating the types.

Therefore, I thought that if there is an object that handles meta information of the input of the function, it will be easier to handle in a unified I/F.

The same is true for function output.

Also, when trying to express a Java-like Interface in Perl5 such as Function::Interface, it is useful if the input/output of functions is easy to handle.

The current F::I is sticky in the Function::Parameters and Function::Return implementations, and I thought that it could not handle many applications and lacked flexibility.

That's why I created Sub::Meta that can handle meta information including function input and output. I'm glad to try it if it is good! That's all!

Top comments (0)