我有一个关于子程序中的变量何时以及如何释放内存的问题.该脚本是一个例子:
#!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被调用多次时应该更改引用,但无论输入何时更改,输出引用都是固定的.这种现象是否可以推断,在整个脚本结束之前,子程序中变量占用的内存永远不会被释放?否则,我的结果是不寻常的?
A($i)可以方便地在perl认为的任何位置调用分配新的arrayref.A()如果阻止数组被释放,您将看到在不同地址创建的新数组.
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)