mirod,
I love closures. See How A Function Becomes Higher Order, and Understanding And Using Iterators for examples ;-)

I believe I did a poor job of explaining my goal and my hangup. I am processing a log with millions of XML messages. Each message must be converted to a distinct perl data structure. While I can see several ways of accomplishing this, none of them seem to let me have my cake and eat it too.

To use a closure in the way you describe, I would need a factory to create a brand new closure for each message and either instantiate a new instance of XML::Twig for each message or call $twig->setTwigHandlers() in between each call to $twig->parse(). The alternative would be to leave the XML::Twig object alone and perform a deep copy and "reset" of reference that was closed over in between each message.

My comprimise - which I am fine with, was to write my own dispatch table where I could do something akin to:

# ... my $twig = XML::Twig->new(); while (<$fh>) { chomp; my $msg = {}; $twig->parse($_); for my $child ($twig->root->children) { my $handler = $child->tag; if ($dispatch{$handler}) { $dispatch{$handler}->($child, $msg); } else { die "Haven't written handler for '$handler' yet"; } } # do something with $msg }

I asked for advice here to make sure I wasn't missing anything obvious. I will certainly check out simplify.

Cheers - L~R


In reply to Re^2: Convert XML To Perl Data Structures Using XML::Twig by Limbic~Region
in thread Convert XML To Perl Data Structures Using XML::Twig by Limbic~Region

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.