Perl: “Variable will not stay shared”

拟墨画扇 提交于 2019-12-03 23:25:20

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.

You need to have an anonymous subroutine to capture variables:

my $innerSub = sub  {
  my $resultVar = doStuffWith($dom);
  return $resultVar;
};

Example:

sub test {
    my $s = shift;

    my $f = sub {
        return $s x 2;
    };  

    print $f->(), "\n";

    $s = "543";

    print $f->(), "\n";
}

test("a1b");

Gives:

a1ba1b
543543

If you want to minimize the amount of size passing parameters to subs, use Perl references. The drawback / feature is that the sub could change the referenced param contents.

my $dom = someBigDOM;
my $resultVar = doStuffWith(\$dom);


sub doStuffWith {
   my $dom_reference = shift;
   my $dom_contents = $$dom_reference;
   #...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!