Nested subroutines and Scoping in Perl

前端 未结 4 717
迷失自我
迷失自我 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条回答
  •  旧时难觅i
    2020-12-08 22:17

    The "official" way to create nested subroutines in perl is to use the local keyword. For example:

    sub a {
        local *b = sub {
            return 123;
        };
        return b();  # Works as expected
    }
    
    b();  # Error: "Undefined subroutine &main::b called at ..."
    

    The perldoc page perlref has this example:

    sub outer {
        my $x = $_[0] + 35;
        local *inner = sub { return $x * 19 };
        return $x + inner();
    }
    

    "This has the interesting effect of creating a function local to another function, something not normally supported in Perl."

提交回复
热议问题