http://www.perlmonks.org?node_id=1011290

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

Greeting wise brothers.

I am looking a Moose class reprentation of a binary file format. (The binary file is the metadata file format used by Humax Digital satelite TV recevers. Documented here: http://foxsatdisk.wikispaces.com/.hmt+file+format)

Seeing as the Moose BestPractices discorage overiding new(), the approach I am taking is to insert the raw data as a field in the class, and then have a large number of lazy builders to extract fields. My API currenlty looks like this:

my $hmt_data = new Binary::Humax::hmt_data(); # Object will be us +eless as it contains no data $hmt_data->raw_from_file($path_name); # At this point onl +y the 'rawData' field is populated my $field = $hmt_data->startTime(); # Invokes a lazy bu +ilder to extract the field.

Some of the code in the class looks like this

use DateTime; use Moose; # The raw data that all the fields are extracted from. has 'rawDataBlock' => ( is => 'rw', isa => 'Str', ); # All the fields extracted from the raw data block are lazy using buil +ders below. has 'lastPlay' => ( lazy_build => 1, is=>'rw', isa=>'Int'); has 'ChanNum' => ( lazy_build => 1, is=>'rw', isa=>'Int'); has 'startTime' => ( lazy_build => 1, is=>'rw', isa=>'DateTime') +; has 'fileName' => ( lazy_build => 1, is=>'rw', isa=>'Str'); [...] sub _build_lastPlay { my $self = shift @_; return unpack('@5 S', $self->rawDataBlock() ); } sub _build_ChanNum { my $self = shift @_; return unpack('@17 S', $self->rawDataBlock() ); } sub _build_startTime { my $self = shift @_; my $epoch = unpack('@25 N', $self->rawDataBlock() ); return DateTime->from_epoch( epoch => $epoch, time_zone => 'GMT' ) +; } sub _build_fileName { my $self = shift @_; return unpack('@33 A512', $self->rawDataBlock() ); }

My problem is that there are rather a lot of those lazy builders, and they are all similar and repetitive. Is there a way I can make all the fields share the same lazy builder, perhaps by putting the unpack information as an attribute to the field definition?

Secondly, when complete, I plan to upload the module to CPAN. Have I chosen a good name for it, or should it live in a different name space?