I was wondering if it's possible to declare a global variable within a subroutine in Perl so that I can use that variable in a hooked void function, but limiting the damaging effects of the global by having it declared in a subroutine.
我想知道是否可以在Perl子例程中声明一个全局变量,这样我就可以在一个连接的void函数中使用这个变量,但是通过在子例程中声明它来限制全局变量的破坏性影响。
So the subroutine uses XML::Parser
to collect the IDs of a bunch of elements, in a manner similar to:
因此,子例程使用XML::Parser来收集一系列元素的id,其方式类似于:
sub getRecipeIDs {
my $recipe = shift;
my @elements = ();
my $parser = new XML::Parser(Style => 'Tree',
Handlers => {
Start => sub {
my ($expat, $element, %attrs) = @_;
if ($element eq 'recipe') {
push @elements, $attrs{id};
}
}});
$parser->parse($recipe);
return @elements;
}
I'm also using strict
in my script.
我在脚本中也使用了strict。
So I want to declare @elements
in such a way that it is local to getRecipeIDs
but is visible to the anonymous subroutine.
因此,我想以这样的方式声明@元素,它是getrecipeid的局部变量,但对匿名子例程是可见的。
Thanks for your time, any help is greatly appreciated.
谢谢您的时间,任何帮助都是非常感谢的。
3 个解决方案
#1
5
It should already work the way in which you've written your example. What you're doing with "my $func = sub { ... }
" is you create a closure which has access to the enclosing scope's variables -- in this case @elements
.
它应该已经按照您编写示例的方式工作了。你用“我的$func = sub{…”}“您是否创建了一个闭包,它可以访问封闭范围的变量——在本例中是@elements。
#2
3
my
is fine. Lexical variables are visible in nested scopes, such as anonymous subroutines.
我很好。在嵌套范围(如匿名子例程)中可以看到词汇变量。
Your code should therefore work as-is.
因此,您的代码应该按原样工作。
#3
3
Your code should work fine as it stands
您的代码应该能够正常工作
Despite the depth of the anonymous subroutine, its scope includes the lexical array @elements
and it can access it freely
尽管匿名子例程的深度很大,但它的范围包括lexical数组@elements,并且可以*访问它
Furthermore the subroutine counts as a reference to the array, so it will not be garbage collected when it goes out of scope at the end of the call to getRecipeIDs
此外,子例程计数作为对数组的引用,因此在对getrecipeid的调用结束时,当它超出范围时,不会被垃圾收集
#1
5
It should already work the way in which you've written your example. What you're doing with "my $func = sub { ... }
" is you create a closure which has access to the enclosing scope's variables -- in this case @elements
.
它应该已经按照您编写示例的方式工作了。你用“我的$func = sub{…”}“您是否创建了一个闭包,它可以访问封闭范围的变量——在本例中是@elements。
#2
3
my
is fine. Lexical variables are visible in nested scopes, such as anonymous subroutines.
我很好。在嵌套范围(如匿名子例程)中可以看到词汇变量。
Your code should therefore work as-is.
因此,您的代码应该按原样工作。
#3
3
Your code should work fine as it stands
您的代码应该能够正常工作
Despite the depth of the anonymous subroutine, its scope includes the lexical array @elements
and it can access it freely
尽管匿名子例程的深度很大,但它的范围包括lexical数组@elements,并且可以*访问它
Furthermore the subroutine counts as a reference to the array, so it will not be garbage collected when it goes out of scope at the end of the call to getRecipeIDs
此外,子例程计数作为对数组的引用,因此在对getrecipeid的调用结束时,当它超出范围时,不会被垃圾收集