in reply to Variable scope with XML::Parser

That is a strange question. The answer is inside. The hdl_start subroutine is called, from inside of the library, with the three arguments: the object, the tag & a hash of attributes (if you count that hash as one), it then sets the global $tag and $name variables. So there is no problem with your code.

Replies are listed 'Best First'.
Re: Re: Variable scope with XML::Parser
by Basilides (Friar) on Mar 17, 2003 at 12:43 UTC
    OK, so global variables, which usually get a right slagging off, are the only solution here?
      Ah that! For sure you can resolve this for many ways. Here is one (it might be a bit convoluted, I admit):
      my $p = new XML::Parser (Handlers => {Start => sub{hdl_start($tag, $na +me, @_)}, ...
      and
      sub hdl_start { $_[0] = $_[2]; $_[1] = $_[3]; }
      What I use here is an anonymous subroutine as the handler, and I've changed the hdl_start subroutine to change it's two first parameters ($_[0] and $_[1]).
      Have just read the Streams chapter in Perl and XML (a book I highly reccomend), I offer the following solution - you can pass a class to XML::Parser instead of the specific handlers. You can then have the class maintain the state, instead of global variables.

      ------
      We are the carpenters and bricklayers of the Information Age.

      Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

      OK, so global variables, which usually get a right slagging off, are the only solution here?

      Well, you can use closures to avoid globals, but a better solution is to not use XML::Parser directly, but use SAX instead. Or depending on your application, an even better solution might be to use a higher level module like XML::Twig or XML::XPath (etc).