in reply to Saving values in a parser

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); }

Replies are listed 'Best First'.
Re: Re: Saving values in a parser
by AidanLee (Chaplain) on Jul 11, 2001 at 20:46 UTC
    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.