Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Journal of ambs (3914)

Monday June 09, 2008
03:52 PM

Generating methods

[ #36634 ]
I wrote a new module. I am not sure yet of its utility, but it is already on CPAN. It is named LaTeX::Writer::Simple. Also, not sure yet if its interface will be the one available at the moment. But I would like to write about other thing: generating methods. It is cool to define methods during runtime:

BEGIN {
    @EXPORT = (qw/document p/);

    sub _def {
        my ($name, $sub) = @_;

        no strict 'refs';
        my $x = "LaTeX::Writer::Simple::$name";
        *$x = $sub;
        push @EXPORT, $name;
    }

    my @nl_commands = (qw/part chapter section
                          subsection subsubsection caption/);
    for my $c (@nl_commands) {
        _def($c, sub { _newcommand($c, @_)."\n" });
    }

    ...

It is just wonderful. And what I really liked was that Test::Pod::Coverage detects those methods, and complains about their lack of coverage. Wonderful!

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • I love generating named routines.

    Perhaps you would enjoy Sub::Exporter [cpan.org].
    --
    rjbs
  • I'm all for this technique, and I use it myself, so I'll just limit myself to some feedback on the code.

    First, why are you using @EXPORT rather than @EXPORT_OK? That warning in Exporter is there for a reason.

    Second, why are you using a BEGIN block? This code is in a module, which means that there is an implicit BEGIN block on your code already. Therefore adding another one is just semantic noise. You certainly don't need it for the sake of Exporter, since Exporter's import method isn't called until afte
  • Well, the _def function was there just to make it easier to read, but you are correct that it is an extra indirection. Thanks for the comments ;)
    • Oh, and there is another reason about defining a _def. I am using this code to define functions in four or five different places. This makes it easier to maintain.

      Sorry for the indirection ;)