July 22, 2011

Vim trick to generate POD

So, I hate writing Perl. I'll just throw that out there. When I do, I try to make it as easy as possible on myself. For example, I write OO Perl. You can laugh at me all you want, but I find that the APIs are easier to deal with, and I like the way the scripts read in the end.

Part of the API I'm writing involves a lot of class member variables. For class variables, I use file-scoped lexicals (from man perltooc):

package Some_Class;
my %ClassData = (
    CData1 => "",
    CData2 => "",
);
for my $datum (keys %ClassData) { 
    no strict "refs";
    *$datum = sub { 
        shift; # XXX: ignore calling class/object
        $ClassData{$datum} = shift if @_;
        return $ClassData{$datum};
    };
}

 So what's the big deal, you ask? Well, it lets me do things like this:

my $foo = Foo::new();
$foo->CData1("foo");
etc.

So, generating documentation for these is pretty trivial. I do inline POD, so it'll look something like this:

=head1 MEMBERS

=over

=item b<CData1([$CData1])>

=item b<CData2([$CData2])>

=cut

Or you can replace the $CDatax with a variable type, if you want.

I'm working on a class right now with about 20 member variables. I wanted to generate documentation for all of the member variables, so that you could do perldoc MyClass to get the list instead of having to look at code.

There is a very easy way to do this! I use vim as my editor, so I did the following:
  1. Visually select all of the contents of the %ClassData hash.
  2. Copy the text (y) and paste it (p) into a documentation block
  3. Highlight all of the pasted text
  4. Unindent it (<<)
  5. :s/\(.*\) =>.*/=item B<\1([$\1])>\r
  6. Enter
Voila! You have created documentation (or stubs for the really anal retentive or bad) for all of your member variables.

0 comments:

Post a Comment