Perl子例程中的变量不会释放内存

Eze*_*Kuo 4 perl subroutine

我有一个关于子程序中的变量何时以及如何释放内存的问题.该脚本是一个例子:

#!perl/bin/per
use strict;
sub A{
    my $x= shift;
    return ([$x]);
}
for my $i (1..10){
    my $ref= &A($i);## the input changes in each round
    my $ref2= &A(9);## the input is fixed in each round
    print "$ref\t";
    print "$ref2\n";
}
Run Code Online (Sandbox Code Playgroud)

并且屏幕上的输出是:

ARRAY(0x996e98) ARRAY(0x9b50c8)
ARRAY(0x996e98) ARRAY(0x9b50c8)
ARRAY(0x996e98) ARRAY(0x9b50c8)
ARRAY(0x996e98) ARRAY(0x9b50c8)
ARRAY(0x996e98) ARRAY(0x9b50c8)
ARRAY(0x996e98) ARRAY(0x9b50c8)
ARRAY(0x996e98) ARRAY(0x9b50c8)
ARRAY(0x996e98) ARRAY(0x9b50c8)
ARRAY(0x996e98) ARRAY(0x9b50c8)
ARRAY(0x996e98) ARRAY(0x9b50c8)
Run Code Online (Sandbox Code Playgroud)

我预计在子程序A被调用多次时应该更改引用,但无论输入何时更改,输出引用都是固定的.这种现象是否可以推断,在整个脚本结束之前,子程序中变量占用的内存永远不会被释放?否则,我的结果是不寻常的?

pil*_*row 8

  1. A($i)可以方便地在perl认为的任何位置调用分配新的arrayref.
  2. 该数组引用返回到您的循环体,并存储在一个词法范围到该循环体的变量中.
  3. 在循环的底部,变量超出范围,并且由于没有其他内容引用该arrayref,因此释放了arrayref.
  4. 因此,以前保持arrayref的存储器位置再次方便地可用,并且在下次需要时...在下次调用时重用 A()
  5. 转到1

如果阻止数组被释放,您将看到在不同地址创建的新数组.

my @a;
for my $i (1..10){
    my $ref= &A($i);## the input changes in each round
    my $ref2= &A(9);## the input is fixed in each round
    print "$ref\t";
    print "$ref2\n";
    push @a, $ref, $ref2;
}
Run Code Online (Sandbox Code Playgroud)