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

In reply to Re: Saving values in a parser by tadman
in thread Saving values in a parser by swiftone

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.