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

Greetings Wise Monks,

Normally when I have a perl problem I at least have an idea where to start looking but I think I'm missing something fundamental (well that and "filehandle" "filter" "io" are crappy search terms) So I'm hoping that someone here will has a suggestion of where I should start.

I have a huge (200+Mb to 2Gb with no line breaks) XML file that gets inserted into a SQL DB every week. It uses XML::Parser::PerlSAX to avoid trying to load the whole thing into memory. However the XML generator (which is outside of my control) frequently generates invalid XML, now I have a number of regexp substitutions that fix up the file but pre-processing to a temp file is a _real_ pain. so I'd like to switch to stream filter that could sit in between the input filehandle and PerlSAX. However as I not totally comfortable with the underlying C-ness of perl IO I'm at a bit of a loss on how to start.

I could just pipe the input through another perl script but how do I hook into the read request (overloading the < > opperator?) so that I only read from the source file when PerlSAX tries to read from its filehandle. If I wrote a straight STDIN->process->STDOUT type filter my gut says that it would go all out reading the XML (most likely faster that PerlSAX would read from the other end) as run out of buffering space.

What I really want is some kind of callback on a filehandle when a read request is issued, such that I could then read from the source, filter it and provide the result to PerlSAX via a filehandle. But don't have enough mojo to know where to start.

I looked through all the Filter::*, IO:: CPAN modules and found an output filehandle filter (Filter::Handle) but I didn't seem adaptable.

Anyone done anything like this? Or perhaps suggest an alternate approach. Any suggestions welcome.

Replies are listed 'Best First'.
Re: Input Filehandle Filtering
by SilentMobius (Initiate) on Aug 22, 2006 at 16:24 UTC

    Grr I was logged in a moment ago, Damn you cookies!

    This one is mine

      SilentMobius,
      I would recommend changing your theme or adding some custom CSS so that you can easily distinguish when you are logged in visually. I prefer the red theme myself.

      Additionally, look at PerlIO::Via. See this for an extremely simple example and this one for a more complete example.

      Update: Added links to examples.

      Cheers - L~R

      No cookie for you! Come back, one day! NEXT!!