Perl 中的嵌套子程序和范围 [英] Nested subroutines and Scoping in Perl

查看:29
本文介绍了Perl 中的嵌套子程序和范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写 Perl 已经有一段时间了,总是发现新事物,我只是遇到了一些有趣的事情,我没有解释,也没有在网络上找到.

I'm writing Perl for quite some time now and always discovering new things, and I just ran into something interesting that I don't have the explanation to it, nor found it over the web.

sub a {
   sub b {
     print "In B
";
   }
}
b();

为什么我可以从它的范围之外调用 b() 并且它可以工作?

how come I can call b() from outside its scope and it works?

我知道这样做是一种不好的做法,但我不这样做,我在这些情况下使用了封闭式等,但刚刚看到.

I know its a bad practice to do it, and I dont do it, I use closured and such for these cases, but just saw that.

推荐答案

子程序在编译时存储在全局命名空间中.在您的示例中,b();main::b(); 的简写.要将函数的可见性限制在范围内,您需要为变量分配匿名子例程.

Subroutines are stored in a global namespace at compile time. In your example b(); is short hand for main::b();. To limit visibility of a function to a scope you need to assign an anonymous subroutines to a variable.

命名子例程和匿名子例程都可以形成闭包,但是由于命名子例程如果嵌套它们只会编译一次,因此它们的行为并不像很多人预期的那样.

Both named and anonymous subroutines can form closures, but since named subroutines are only compiled once if you nest them they don't behave as many people expect.

use warnings;
sub one {
    my $var = shift;
    sub two {
        print "var: $var
";
    }
}
one("test");
two();
one("fail");
two();
__END__
output:
Variable "$var" will not stay shared at -e line 5.
var: test
var: test

Perl 中允许嵌套命名子例程,但这几乎可以肯定是代码执行错误的标志.

Nesting named subroutines is allowed in Perl but it's almost certainly a sign that the code is doing someting incorrectly.

这篇关于Perl 中的嵌套子程序和范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆