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

This a question that addresses HTML::Parser, XML::Parser, and Parse::RecDescent.

Every intro article and related code I've seen using these modules uses them to translate between formats. So far so good, but now I need to understand positional information. (For example, in XML::Parser, I have a series of <elementX> <date>Text</date><amount>Amount</amount></elementX> sets. I need to recognize what tagset text is inside of, and then associate that data with the order of the outer tags. (i.e. I want to end up with something like [{date=>'Text', amount =>'Amount'}, {date=>'Text2',amount=>'Amount2'}...]

The simple parsers I have to examine use global variables. The documentation seems to imply there are more advanced methods of dealing with this, but they all assume more parser experience than I have.

What am I missing? Is there some way to pass objects into my parse handlers, or make those handlers part of an object?

Replies are listed 'Best First'.
Re: Saving values in a parser
by tadman (Prior) on Jul 11, 2001 at 20:27 UTC
    Instead of using "global" variables, you can use sub-local pseudo-global variables. These are "local" to your function by definition, but are available to sub-functions, such as anonymous subs that you define. This avoids problems when you use the sub more than once, such as if you are using it recursively.

    Here's an example of the pseudo-global variables using HTML::Parser, and hopefully it will help you with your particular application.

    The theory is that you build a stack of tags that you are inside. The only catch is that some tags don't have pairs, so they don't get shut off properly. An exception table might be handy for this, so in this program there is a rudimentary list of simple tags that do not get closed. This prevents them from accumulating endlessly, as BR would tend to do.
    sub parseur { my $stuff = shift; # Build a hash out of a list of "atomic" tags, # i.e. tags which are not normally closed. my %atomic = map {($_=>1)} qw [ hr br p img li option ]; my @stack; my $start_h = sub { my ($tagname,$attr) = @_; push (@stack, $tagname) unless $atomic{$tagname}; }; my $end_h = sub { my ($tagname) = @_; # Find the last entry in the stack which corresponds... foreach my $i ($#stack .. 0) { if ($stack[$i] eq $tagname) { # ...and remove it. splice (@stack, $i, 1); } } }; my $parser = new HTML::Parser ( start_h => [ $start_h, 'tagname,attr' ], end_h => [ $end_h, 'tagname' ], ); $parser->parse ($stuff); }
      This is pretty close to the approach i use as well, except that i usually dispense with the top-level subroutine and use an anonymous block instead. I also, therefore, need to put the $parser itself outside of that block. However, most of my classes that use XML::Parser have the parser as part of the class's data, so evey new object uses the same parser. Saves on resources.