Store a Moose Object with PDL as Attribute

I am new to Moose and doing everything well until I get trapped using PDL as a property. I want to be able to write an object to a file (I used use MooseX::Storage; with Storage('io' => 'StorableFile'); and this object has a PDL attribute as an attribute. PDL::IO::Storable provides the necessary methods for using Storable in this way, however, I don’t understand how to do this in the Muse.

Here is an example, it is a little long, I know, but it is as minimal as I can do it:

 #!/usr/bin/perl package LinearPDL; use Moose; use PDL::Lite; use PDL::IO::Storable; use MooseX::Storage; with Storage('io' => 'StorableFile'); has 'length' => (is => 'ro', isa => 'Num', required => 1); has 'divisions' => (is => 'ro', isa => 'Int', required => 1); has 'linear_pdl' => (is => 'ro', isa => 'PDL', lazy => 1, builder => '_build_pdl'); sub _build_pdl { my $self = shift; my $pdl = $self->length() / ( $self->divisions() - 1 ) * PDL::Basic::xvals($self->divisions()); return $pdl; } no Moose; __PACKAGE__->meta->make_immutable; use strict; use warnings; my $linear_pdl = LinearPDL->new('length' => 5, 'divisions' => 10); print $linear_pdl->linear_pdl; $linear_pdl->store('file'); # blows up here! my $loaded_lpdl = load('file'); print $loaded_lpdl->linear_pdl; 

I think I might have to create a PDL type or even pack a PDL into something (using MooseX::NonMoose::InsideOut ), but maybe someone can save me from this (or point me on the right path , if so).

+7
source share
2 answers

You do not say what is really wrong. When you guess, you will need to tell MooseX :: Storage how to handle the PDL object using PDL Storable hooks. The documentation for this function in MooseX :: Storage is very poor, but MooseX :: Storage :: Engine has an add_custom_type_handler() method that accepts a type name (PDL in your case) and HashRef handlers.

 MooseX::Storage::Engine->add_custom_type_handler( 'PDL' => ( expand => sub { my ($data) = @_; ... }, collapse => sub { my ($object) = @_; ... }, ) ); 

Pass by #moose on irc.perl.org or the Moose mailing list and ask.

[Edit: update the test- based example.]

+7
source

Joel's question and the answer from perigrin helped me solve the storage problem that sat in my head for a while. I am posting a working example here. It does not use PDL, but is connected and may help someone in the future.

 { package MVR; use Moose; use MooseX::Storage; use Math::Vector::Real; use Data::Structure::Util qw (unbless); with Storage('format' => 'JSON', 'io' => 'File'); MooseX::Storage::Engine->add_custom_type_handler( 'Math::Vector::Real' => ( expand => sub {my $v = shift; Math::Vector::Real->new(@{$v})}, collapse => sub {my $mvr = shift; return (unbless($mvr)) }, ) ); has 'mvr' => (is => 'rw', isa => 'Math::Vector::Real'); 1; } use Math::Vector::Real; my $p = MVR->new(mvr => V(0,1,3)); print $p->dump; $p->store('my_point.json'); my $p1 = MVR->load('my_point.json'); print $p1->dump; 
+1
source

All Articles