Parse::FixedRecord - object oriented parser for fixed width records
Assuming you have data like this:
Fred Bloggs | 2009-12-08 | 01:05 Mary Blige | 2009-12-08 | 00:30
To create a parser:
package My::Parser; use Parse::FixedRecord; # imports strict and warnings extends 'Parse::FixedRecord::Row'; column first_name => width => 4, isa => 'Str'; pic ' '; column last_name => width => 6, isa => 'Str'; pic ' | '; column date => width => 10, isa => 'Date'; pic ' | '; column duration => width => 5, isa => 'Duration'; 1;
In your code:
use My::Parser; while (my $line = <$fh>) { eval { my $object = My::Parser->parse( $line ); say $object->first_name; do_something() if $ $object->duration->in_units('mins') > 60; }; }
Parse::FixedRecord is a subclass of Moose with a simple domain specific language (DSL) to define parsers.
Parse::FixedRecord
You may use any type constraints you like, as long as they have a coercion from Str. If you wish to output row objects in the same format, they should also have an overload.
Parse::FixedRecord provides Duration and DateTime constraints for you out of the box.
Duration
DateTime
To define the class, simply apply column and has for each field, in the order they appear in your input file. They are defined as follows:
column
has
This is a specialisation of Moose's has, which applies the Parse::FixedRecord::Column trait.
Moose
You must supply a 'width' parameter. Unless you specify otherwise, the trait will default to is => 'ro', so will be readonly.
is => 'ro'
column foo => width => 10; # readonly accessor column bar => width => 5, is => 'rw'; # read/write column baz => width => 5, isa => 'Some::Type';
pic
You may also supply delimiters. As this is a fixed record parser, allowing delimiters may seem odd. But it may be convenient for some (odd) datasets, and in any case, there is no requirement to use it.
column foo => width => 5; pic ' | '; column bar => width => 5;
i.e. the record consists of two 5-char wide fields, split by the literal ' | '.
' | '
$parser->parse
my $obj = $parser->parse( $line );
If the column and pic definitions can be matched, including any type constraints and object inflations, then a Moose object is returned.
Otherwise, an error is thrown, usually by the Moose type constraint failure.
(C) osfameron 2009, <osfameron@cpan.org>
For support, try emailing me, or grabbing me on irc #london.pm or #moose on irc.perl.org
This module is released under the same terms as Perl itself.
To install Parse::FixedRecord, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Parse::FixedRecord
CPAN shell
perl -MCPAN -e shell install Parse::FixedRecord
For more information on module installation, please visit the detailed CPAN module installation guide.