Nested subroutines and Scoping in Perl

前端 未结 4 712
迷失自我
迷失自我 2020-12-08 22:04

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

4条回答
  •  轮回少年
    2020-12-08 22:35

    The following prints 123.

    sub a {
        $b = 123;
    }
    
    a();
    print $b, "\n";
    

    So why are you surprised that the following does too?

    sub a {
        sub b { return 123; }
    }
    
    a();
    print b(), "\n";
    

    Nowhere is any request for $b or &b to be lexical. In fact, you can't ask for &b to be lexical (yet).

    sub b { ... }
    

    is basically

    BEGIN { *b = sub { ... }; }
    

    where *b is the symbol table entry for $b, @b, ..., and of course &b. That means subs belong to packages, and thus can be called from anywhere within the package, or anywhere at all if their fully qualified name is used (MyPackage::b()).

提交回复
热议问题