Sign in to PrePAN

MooseX::FileBased Read and prepare parsing of file (or glob) data from some source

In Review


           package MyClassThatDoesStuffToAFile;

           sub parse {
               my $self = shift;

               # ... do stuff, $self->fh available

           with "MooseX::FileBased";

           ## ... and in some nearby code:

           my $obj = MyClassThatDoesStuffToAFile->new({ file => "some_file.txt" });
           ## optionally:

           my $obj = MyClassThatDoesStuffToAFile->new({ file => "some_file.txt", encoding => "utf8" });
           ## encoding can be anything that binmode's encoding() can understand.

           print $obj->filename; # "some_file.txt"
           print $obj->size;     # size of some_file.txt

           ## - OR -

           my $fh = IO::File->new( "< some_file.txt" );
           ## you are now responsible for encoding on this handle!

           my $obj = MyClassThatDoesStuffToAFile->new({ file => $fh });

           ## no filename nor file size available

           ## - OR -

           my $file_content = read_file( "some_file.txt" );
           my $obj = MyClassThatDoesStuffToAFile->new({ file => \$file_content });

           ## you are now responsible for encoding on this data
           ## no file name nor file size available


I often write modules to parse some specific file format for some specific task. Often these are files from lab instruments.

They sometimes comes in xml, sometimes csv and sometimes some ooxml-like zipped archive with xml files.

Regardless of format, I found myself repeating code to read it from:

a) a filename b) a file handle c) reference to content

If it were a filename I repeated the same errors if it wasnt found or readable. etc.

I also found myself calling parse() in sub new every time.

This module does all this, and nothing more. To me whenever I work with objects that represent single files, this module (which I have written) makes me copy less code.

I have found some similar examples on cpan, but I were for different reasons not quite happy with them. They were either long since maintained or not quite addressing the same problem.

This module could be extended to also support URI objects, should probably also support reading a single argument as a file reference, ie no need to give the moose argument { file => "foo" }, just "foo" for simple cases.


I don't see anything in this module that would make it a Moose extension - so it doesn't really belong in that namespace. MooseX:: modules are not for things that simply use Moose, but actually extend or modify its functionality in some way.
You are right, this is the wrong name for this module.
How about File::Parser

Please sign up to post a review.