The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Parse::FixedRecord - object oriented parser for fixed width records

VERSION

version 0.06

SYNOPSIS

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

  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;
    };
  }

DESCRIPTION

Parse::FixedRecord is a subclass of Moose with a simple domain specific language (DSL) to define parsers.

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.

Definition

To define the class, simply apply column and pic for each field, in the order they appear in your input file. They are defined as follows:

column

This is a specialisation of Moose's has, which applies the Parse::FixedRecord::Column trait.

You must supply a 'width' parameter. Unless you specify otherwise, the trait will default to is => 'ro', so will be readonly.

  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 ' | '.

ignore

Like pic, but the actual contents of the delimiter are ignored. The argument is the field width.

  column foo => width => 5;
  ignore 3;
  column bar => width => 5;

Parsing

$parser->parse

  my $obj = My::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.

AUTHOR

osfameron <osfameron@cpan.org>

COPYRIGHT AND LICENSE

This software is copyright (c) 2012 by osfameron.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.