2

如果我有以下代码

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.
    }
}

假设a_section仅由 调用a,我会遇到内存泄漏、变量可靠性或其他问题吗?

我正在探索这个作为替代方案,这样我就可以避免传递$ida_section.

4

1 回答 1

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!!!!

你可以这样做:

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);
}

(您可以使用递归调用内部子程序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);
}

__SUB__->(...)如果您想递归调用内部子程序以避免内存泄漏,请使用,在 Perl 5.16+ 中可用。)

于 2012-05-16T15:47:37.827 回答