Perl:有没有办法将元数据与函数相关联

Perl: Is there any way to associate meta data with functions

将元数据与函数相关联会非常有用。

例如,在web框架中,页面请求通常由控制器中的函数处理。

在其他地方,指定了 URL 和函数之间的映射。

如果能写出这样的东西会很有用:

sub object_list {
  ...  # page rendering code
} = {
  handles_url => '/objects',  # the URL this function handles
  is_action => 1,             # False if this is just a utility function
  requires_login => 1,        # True if a login is required to access this action
}

这样做的优点是:

我只是好奇如果:

我确实多次遇到过这个用例,例如将描述和帮助文本相关联或解析信息与 "command handler" 子项。人们采用了多种方法,但我采用的方法是使用子例程属性。我写了一个完整的 CPAN 模块,Attribute::Storage,来帮助声明和访问东西。

例如(直接从模块文档中引用),您可以安排为您的命令处理程序提供以下元数据:

sub do_copy
   :Description(Copy from SOURCE to DESTINATION)
   :Description(Optionally preserves attributes)
   :Argument("SOURCE")
   :Argument("DESTINATION")
   :Option("attrs")
   :Option("verbose")
{
   ...
}