Variables in Perl routines do not free memory

My question is when and how variables in a routine free memory. The script is an example:

#!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";
}

and the outputs on the screen:

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)

I expected links to be changed when subroutine A was called more than once, but the output links were fixed regardless of when the input was changed or not. Can a phenomenon detect that the memory occupied by a variable in routines can never be released until the whole script has finished? Otherwise, my result is unusual?

+4
source share
1 answer
  • The call A($i)allocates a new array anywhere where perl finds it convenient to access.
  • , .
  • , , arrayref .
  • , , , ... A()
  • goto 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;
}
+8

All Articles