我有一个关于子程序中的变量何时以及如何释放内存的问题。该脚本就是一个例子:
#!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";
}
屏幕上的输出是:
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)
我预计在子程序A被多次调用时应该更改引用,但无论何时更改输入,输出引用都是固定的。这种现象是否可以推断,在整个脚本结束之前,子程序中变量占用的内存永远不会被释放?否则,我的结果是不寻常的?
答案 0 :(得分:8)
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;
}