Perl中的嵌套子例程和作用域 [英] Nested subroutines and Scoping in Perl

查看:87
本文介绍了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\n";
   }
}
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\n";
    }
}
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天全站免登陆