CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Are local variables automatically deleted after a subroutine ends?

 



nevildev
Novice

Aug 20, 2010, 4:41 AM

Post #1 of 4 (650 views)
Are local variables automatically deleted after a subroutine ends? Can't Post

Hello,

Sorry if this has been posted before. This is a concept I've never really fully grasped. In many of my scripts, massive local hash values are created within subroutines. At the end of every subroutine, I've always explicitly deleted the local hash values in fear of unnecessarily using too much memory. Below is sample code to demonstrate what I mean.

Is it necessary to remove local hash variables, or are they automatically deleted at the end of a subroutine?


Code
#!/usr/bin/perl 

sub test {
#Define local variables
my (%file_local,%hash_local);
my $i;

$file_local{'hash_output'} = "hash_dump.txt";
open ( OUT_FILE, ">$file_local{'hash_output'}" ) or die "Can't open $file_local{'hash_output'}";
print OUT_FILE "i,i+1\n";

for ($i = 1; $i <= 100000; $i++) {
$hash_local{$i} = $i-1;
print "$i,$hash_local{$i}\n";
}

close ( OUT_FILE );

#Remove local variables
%file_local = %hash_local = ();
}

print "Exiting program gracefully ...\n"; exit 1;


Thanks!
Evan


shawnhcorey
Enthusiast


Aug 20, 2010, 5:31 AM

Post #2 of 4 (645 views)
Re: [nevildev] Are local variables automatically deleted after a subroutine ends? [In reply to] Can't Post


In Reply To
Is it necessary to remove local hash variables, or are they automatically deleted at the end of a subroutine?


All local variables are automatically deleted at the end of their block unless there's a outstanding reference to them.

__END__

I love Perl; it's the only language where you can bless your thingy.

Perl documentation is available at perldoc.perl.org. The list of standard modules and pragmatics is available in perlmodlib.

Get Markup Help. Please note the markup tag of "code".


nevildev
Novice

Aug 20, 2010, 5:36 AM

Post #3 of 4 (644 views)
Re: [shawnhcorey] Are local variables automatically deleted after a subroutine ends? [In reply to] Can't Post

Thanks Shawn.


BillKSmith
Veteran

Aug 21, 2010, 8:21 PM

Post #4 of 4 (609 views)
Re: [nevildev] Are local variables automatically deleted after a subroutine ends? [In reply to] Can't Post

'Local variables' are something else altogether. (refer perldoc -f local) You should be asking about the scope of 'lexical variables'. Shawn gave a correct but somewhat simplified answer to this question. (Refer 'Variable scoping' section of perldoc perlintro)
Good Luck,
Bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives