Reputation: 927
Imagine I have a referece that points to an array that contains many anonimous arrays. Ex:
my @main_array = ( [1,2,3], [3,4,5], ['a','b','c'] );
my $reference = \@main_array
If later on I'm done using the data from that array and I only have a reference to it, what is the best method to delete that array and free the memory? I usually do the following to free the memory used by data in a simple array:
undef @array
but because I only have a reference to it I thought about doing this
undef @{$reference}
If I do that, wouldn't I just be deleting the references to the anonymous arrays stored in the array (main_array
) and not the actual content of the anonymous arrays?
I guess my question can be simplify as this: Does deleting a reference makes Perl free the memory used by the array, hash or scalar referred by the reference?
Thank you
Upvotes: 1
Views: 1019
Reputation: 385897
If later on I'm done using the data from that array and I only have a reference to it, what is the best method to delete that array and free the memory?
Ideally, just let $reference
go out of scope. Otherwise, you can use $reference = undef;
.
Upvotes: 1
Reputation: 98398
Yes, undef @{$reference}
(or undef @$reference
) will do what undef @array
did. It will free almost all memory used by the array to be reusable by the program.
But there is very rarely any good reason to do this. When your lexical $reference
goes out of scope, the same thing will happen. Explicitly calling undef
on it first will just make your code minutely slower.
Upvotes: 7