On Tue, Sep 17, 2002 at 03:15:44PM -0400, Bernd Prager wrote:
> I'd like to write a subroutine that parses an XML file.
> I use XML::Parse and one way that works is to define
> subroutines with the name of an XML tag and every appearance
> of that tag calls the appropriate subroutine.
> 
> Since I want to have this procedure entirely encapsulated in 
> my funtion I end up defining nested subroutines:
> 
> sub myParse {
>    my $content;
>    
>    sub myXMLtag {
>       (... do something with $content...)
>    }
> 
> }
> Now I'm getting error messages "Variable "$content" will not stay shared".

This will not do what you probably think it does.  myXMLtag is a global
function, regardless of whether or not you define it within another
subroutine.  The error message is described in perldiag:

    > echo 'Variable "$content" will not stay shared' | splain
    Variable "$content" will not stay shared (#1)
        (W closure) An inner (nested) named subroutine is referencing a
        lexical variable defined in an outer subroutine.
    
        When the inner subroutine is called, it will probably see the value of
        the outer subroutine's variable as it was before and during the *first*
        call to the outer subroutine; in this case, after the first call to the
        outer subroutine is complete, the inner and outer subroutines will no
        longer share a common value for the variable.  In other words, the
        variable will no longer be shared.
    
        Furthermore, if the outer subroutine is anonymous and references a
        lexical variable outside itself, then the outer and inner subroutines
        will never share the given variable.
    
        This problem can usually be solved by making the inner subroutine
        anonymous, using the sub {} syntax.  When inner anonymous subs that
        reference variables in outer subroutines are called or referenced, they
        are automatically rebound to the current values of such variables.


> I read something about anonymous functions to prevend this error but
> I can't do that here since XML::Parse requires the function names
> the same as the XML tags.

I assume you mean XML::Parser.  Are you using the 'Subs' style?  The
information you've given so far is too little to formulate any advice.  What
does myParse() do?  How is it called?  How are you calling XML::Parser?

It may be the 'Subs' style is not appropriate for your problem.


Michael
--
Administrator                      www.shoebox.net
Programmer, System Administrator   www.gallanttech.com
--

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to