martes, 7 de septiembre de 2010

Capture the flag with Moose

In today's post, I'll show some ways to get program options via flags (--flags) I discovered recently.

CPAN is crowded with Getopt::* modules, but I'm going to explore the Moose universe.

Moose

At $work, we often have write commandline apps that end with lots of parameters and flags, and 'shift @ARGV' is not an elegant nor flexible solution. I've been using GetOpt::Long for years, but now, using Moose, I discovered an extension Called MooseX::Getopt.


MooseX::Getopt

This Moose eXtension allows you to fill attributes of an object directly from commandline.


We just have to use MooseX::Getopt in our Class, and change the creation of the object from Foo->new to Foo->new_with_options.

Tada!



Now, our program can get all Foo's attributes through the commandline. Note that if you try an invalid flag, it will output the accepted ones.

- But wait, I do not want to allow users initialize all attrs.

Ok, then we should hide the attr under a name beginning with underscore, and set the accessor to our desired name. MooseX::Getopt will understand you don't want it to be accessible through command line options.



MooseX::SimpleConfig

The summum of DWIM is you can also exploit the same introspection capabilities to enable configuration files to setup the execution of the files. And it costs you just one line.
with 'MooseX::SimpleConfig';




The code above will activate an extra flag (--configfile) where you can indicate where to reach the configuration file.

There are more goodies you can add on top of these modules, but for now, I think it's enough for me. :)

From these findings, you can see, Moose is not only a great OOP platform for perl but a higher level base for perl hackers to put stuff on.

Thanks Perl community.

No hay comentarios: