0

It would be very useful to associate meta-data with functions.

For example, in web frameworks, a page request is usually handled by function in the controller.

Elsewhere, the mapping between URLs and functions is specified.

It would be very useful to be able to write something like this:

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
}

The advantages of this are:

  • you have all the info about the function in one place
  • reviewing the code for correctness is easier.
  • things like login checking and sanity checking can be easier.

I'm just curious if:

  • you think this sort of function meta data would be useful.
  • Has anyone come up with a reasonable way to do it in Perl?
  • Are there any other languages that do this sort of thing?
NXT
  • 1,855
  • 2
  • 18
  • 36
  • 4
    [`attributes`?](https://metacpan.org/pod/attributes) – mob Feb 24 '16 at 21:01
  • 4
    Yes, I believe Catalyst uses attributes for this. In contrast, Dancer has DSL wrapped around the sub, rather than having meta data attached to the sub. – ysth Feb 24 '16 at 21:10
  • Not sure exactly what you're after ... did you conside closures? Can do all kinds of things with them. – zdim Feb 24 '16 at 21:48
  • "Do you think this sort of function meta data would be useful?" No. ... Are you trying to re-invent Java Beans? Regardless, as @mob points out, we already have attributes. – Sinan Ünür Feb 24 '16 at 22:32
  • 1
    Can't help but asking: why not turn this around and have a simple class? So the sub is a method with data. You get all requirements, and much more. With that, I'd say that a feature like this would not be useful. – zdim Feb 24 '16 at 22:46

1 Answers1

4

I did encounter this use-case a number of times, for example associating description and help text or parsing information with "command handler" subs. There's a number of approaches that people take, but the approach I took was to use subroutine attributes. I wrote an entire CPAN module, Attribute::Storage, to help with declaring and accessing things.

For example (quoting directly from the module docs), you can arrange to give your command handlers such metadata as:

sub do_copy
   :Description(Copy from SOURCE to DESTINATION)
   :Description(Optionally preserves attributes)
   :Argument("SOURCE")
   :Argument("DESTINATION")
   :Option("attrs")
   :Option("verbose")
{
   ...
}
LeoNerd
  • 8,344
  • 1
  • 29
  • 36