Ben Humphreys

Computational linguistics researcher at Kyoto University, focussing on machine translation. Also learning Japanese, Korean, French and other badassery.
(日本語版)

January 20, 2010 at 12:59pm
Home

MooseX::Getopt, YAML and properties

I was trying to let users specify a set of hierarchical properties from the command line.

This is how you run it from the command line:

foo tmp --yaml_properties="cake: [ bar, cake ]"

YAML STRING: cake: [ bar, cake ]
$VAR1 = {
          'cake' => [
                      'bar',
                      'cake'
                    ]
        };

Code:

package Foo::Command::tmp;

use Moose;
use Moose::Util::TypeConstraints;

extends qw( MooseX::App::Cmd::Command );

use Data::Dumper;
use YAML::Syck;

# Dont know what kind of data structure the YAML will create
subtype 'YAMLProperties' => as 'Ref';

# Want to force the data structure to load from simple Str
coerce 'YAMLProperties'
    => from 'Str'
        => via { 
            my $yaml_string = $_;
            print "YAML STRING: $yaml_string\n";
            return Load( $yaml_string );
        };

# Let Getopt know that YAMLProperties is a string
MooseX::Getopt::OptionTypeMap->add_option_type_to_map(
    'YAMLProperties' => '=s'
);


has yaml_properties => (
    traits        => [ qw( Getopt ) ],
    isa           => 'YAMLProperties',
    is            => 'ro',
    cmd_aliases   => 'yp',
    coerce        => 1,
    documentation => 'YAML-based properties. Gives you access to any data structure. Great!',
);


# Verify parameters
sub run {
    my ($self, $opt, $args) = @_;
    
    print Dumper($self->yaml_properties);
    
    return 1;
}

1;

Notes

  1. benhumphreys posted this