in reply to Re^2: Scope of lexical variables in the main script
in thread Scope of lexical variables in the main script
If you pass a reference to that memory from the: my $trick = "TRICKY"; statement out of a sub, the next time Perl sees the "my", it allocates new memory for it if it sees that what it did before is still in "use" - meaning a reference to it exists. Perl "frees" memory back for its own use when it sees that the reference count to that memory is zero - not well illustrated in this example. The point here is that you get a completely new copy of "TRICKY" every time the sub is called.
My verbage was a bit confusing, but does the code answer the question?
@tricks=(); will "free" the $tricks memory back to Perl (not to the O/S) and Perl will reuse it if it can because no references exists any longer to various memory allocations of "TRICKY".#!/usr/bin/perl use strict; use warnings; my @tricks; for (1..3) { my $ref_to_a_trick = get_a_trick(); push @tricks, $ref_to_a_trick; } print @tricks,"\n"; #SCALAR(0x182b394)SCALAR(0x24920c)SCALAR(0x24925c) #note each "trick reference" points to a different location #@tricks is an array of scalar references foreach my $ref (@tricks) { print "$$ref\n"; #de-reference each "trick" to get the value #TRICKY #TRICKY #TRICKY } sub get_a_trick { my $trick = "TRICKY"; return (\$trick); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Scope of lexical variables in the main script
by sophate (Beadle) on Apr 20, 2012 at 06:53 UTC |