嵌套的Perl subs有什么问题,只在本地调用吗?

Bry*_*eld 2 memory perl scope nested

如果我有以下代码

sub a {
    my $id = shift;
    # does something
    print &a_section($texta);
    print &a_section($textb);
    sub a_section {
        my $text = shift;
        # combines the $id and the $text to create and return some result.
    }
}
Run Code Online (Sandbox Code Playgroud)

假设a_section只被调用a,我是否会遇到内存泄漏,可变可靠性或其他问题?

我正在探索这个作为替代方案,所以我可以避免传递$id给它的必要性a_section.

ike*_*ami 9

首先,它不是私人潜艇.它从外面完全可见.二,你会遇到问题.

$ perl -wE'
   sub outer {
      my ($x) = @_;
      sub inner { say $x; }
      inner();
   }
   outer(123);
   outer(456);
'
Variable "$x" will not stay shared at -e line 4.
123
123     <--- XXX Not 456!!!!
Run Code Online (Sandbox Code Playgroud)

你可以这样做:

sub a {
    my $id = shift;

    local *a_section = sub {
        my $text = shift;
        # combines the $id and the $text to create and return some result.
    };

    print a_section($texta);
    print a_section($textb);
}
Run Code Online (Sandbox Code Playgroud)

(您可以使用递归调用内部子a_section(...).)

要么:

sub a {
    my $id = shift;

    my $a_section = sub {
        my $text = shift;
        # combines the $id and the $text to create and return some result.
    };

    print $a_section->($texta);
    print $a_section->($textb);
}
Run Code Online (Sandbox Code Playgroud)

(__SUB__->(...)如果要以递归方式调用内部子以避免内存泄漏,请使用,可在Perl 5.16+中找到.)