Perl: “Variable will not stay shared”

后端 未结 4 1600
无人共我
无人共我 2021-02-12 13:16

I looked up a few answers dealing with this warning, but neither did they help me, nor do I truly understand what Perl is doing here at all. Here\'s what I WANT it to do:

<
4条回答
  •  梦如初夏
    2021-02-12 14:11

    In brief, the second and later times outerSub is called will have a different $dom variable than the one used by innerSub. You can fix this by doing this:

    {
        my $dom;
        sub outerSub {
            $dom = ...
            ... innerSub() ...
        }
        sub innerSub {
            ...
        }
    }
    

    or by doing this:

    sub outerSub {
        my $dom = ...
        *innerSub = sub {
            ...
        };
        ... innerSub() ...
    }
    

    or this:

    sub outerSub {
        my $dom = ...
        my $innerSub = sub {
            ...
        };
        ... $innerSub->() ...
    }
    

    All the variables are originally preallocated, and innerSub and outerSub share the same $dom. When you leave a scope, perl goes through the lexical variables that were declared in the scope and reinitializes them. So at the point that the first call to outerSub is completed, it gets a new $dom. Because named subs are global things, though, innerSub isn't affected by this, and keeps referring to the old $dom. So if outerSub is called a second time, its $dom and innerSub's $dom are in fact separate variables.

    So either moving the declaration out of outerSub or using an anonymous sub (which gets freshly bound to the lexical environment at runtime) fixed the problem.

提交回复
热议问题