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

I'm trying to create an OO class that will parse an XML file to instantiate itself. I'm using XML::Parser:Expat. My question is: How do I pass OO Method References to the Expat parser? For a non-OO approach I would use:
use XML::Parser:Expat; my $parser = new XML::Parser::Expat; $parser->setHandlers('Start' => \&sh, 'End' => \&eh, 'Char' => \&ch); . . sub sh { my ($p, $el, %atts) = @_; . .
So, if sh, eh and ch are OO Methods, how does this work? Just as important, in the sh, eh and ch methods, will they receive a reference to "$this" as the first parameter? So far I know it's NOT:
sub parseNavigator { my $this = shift; my $parser = new XML::Parser::Expat; $parser->setHandlers('Start' => \&$this->sh, 'End' => \&$this->eh, 'Char' => \&$this->ch); . . sub sh { my ($this, $p, $el, %atts) = @_; . .

"B-)>

Replies are listed 'Best First'.
Re: OO Callback Function Reference
by almut (Canon) on Feb 04, 2010 at 15:53 UTC

    Try closures:

    Start => sub { $this->sh },

    The effect of this is that the current value of $this (the object instance) is being bound to the anonymous sub.

      Though, if your callbacks expect to be passed arguments (which they usually do), then you need to pass those args through to the method call as well. Like so:
      Start => sub { $this->sh(@_) },
Re: OO Callback Function Reference
by roboticus (Chancellor) on Feb 04, 2010 at 15:52 UTC

    FlatBallFlyer:

    Using OO methods would mean that you'd first have to have an object. I would suggest another approach. Connect a "factory" method to the "End" handler to build the object after collecting the object data. You could use the "Start" handler to allocate the hash to collect the data.

    If you're using Moose style OO, it would simplify things as Moose gives you a constructor that accepts a hash of values as a constructor.

    In your "Start" handler, you'll have to register the hash you're building so you can reach it again, and at the "End" handler, you'll want to connect your object to the parent object (which you can access via the aforementioned registration). A simple stack will probably be sufficient for the registration process.

    ...roboticus

Re: OO Callback Function Reference
by Jenda (Abbot) on Feb 08, 2010 at 09:03 UTC

    I think XML::Parser::Expat is a bit too low-level. I'd suggest XML::Rules instead.

    Jenda
    Enoch was right!
    Enjoy the last years of Rome.