ennuikiller has asked for the wisdom of the Perl Monks concerning the following question:

So in ruby I can easily read in a yml file and create objects dynamically corresponding to the yml config. Is there a similar facility in moose or any other object implementation that would make this painless?

Replies are listed 'Best First'.
Re: Dynamically create objects from YAML
by halfcountplus (Hermit) on Oct 17, 2010 at 19:21 UTC

    YAML::XS from CPAN (http://search.cpan.org/dist/YAML-LibYAML/lib/YAML/XS.pm). For example:

    #!/usr/bin/perl -w use strict; package example; # object definition sub new { my $self = {}; $self->{'data'} = pop; return bless($self); } sub getData { my $self = shift; return $self->{'data'} } package Main; use YAML::XS; my $eg = new example("Hello world!\n"); my $save = Dump $eg; # object instance to yaml markup # save yaml markup to file open (EG, '>yaml.test') || die; print EG $save; close(EG); $save = $eg = undef; # clear variables # now load yaml markup from file open (EG, '<yaml.test') || die; $save .= $_ while (<EG>); close(EG); # yaml markup back into object $eg = Load $save; print $eg->getData(); # proof!

    Dump and Load are the YAML::XS commands.

      Or slightly shorter:

      use strict; use warnings; package Example; sub new { my $self = {}; $self->{'data'} = pop; return bless($self); } package main; use YAML qw(DumpFile LoadFile); # it will use YAML::XS if it installed use Data::Dumper; my $eg = Example->new("Hello world!"); my $save = DumpFile('test.yml', $eg); my $rest = LoadFile('test.yml'); warn Dumper $rest;
Re: Dynamically create objects from YAML
by stvn (Monsignor) on Oct 18, 2010 at 19:35 UTC

    You actually have a couple of choices for YAML and Moose.

    First is MooseX::Storage, which is a full fledged serialization framework which no only supports YAML, but also JSON and Storable and will handle both serializing to text or to a file.

    If that is more then you really are looking for, then you might want to take a look at MooseX::YAML which works best with YAML::XS and will reconstruct your Moose object in the correct way using MooseX::Blessed::Reconstruct to do all the dirty work.

    The major difference between these two modules being that MooseX::Storage handles reading and writing, while MooseX::YAML is really mostly just concerned with reading since you would basically just use plain old YAML to do the writing for you.

    -stvn