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: Beginner:
Correct place to declare variables

 



kencl
User

Mar 24, 2001, 11:55 AM

Post #1 of 2 (313 views)
Correct place to declare variables Can't Post

I'm wondering where the correct place to declare variables with my or local within subroutines is. IE, should I do it right at the start, or is it ok to do it within nested loops?

Code
sub whatever { 
my ($string, @array, %hash);
for (my $x = 1; $x < 1000; $x++) {
my $temp = 0;
etc...
}
}

>> If you can't control it, improve it, correlate it or disseminate it with PERL, it doesn't exist!


Jasmine
Administrator / Moderator

Mar 24, 2001, 2:52 PM

Post #2 of 2 (311 views)
Re: Correct place to declare variables [In reply to] Can't Post

Assuming you're using strict (and you should be Smile), the variables need to be declared before they're used. Preferrably being completely encapsulated within the same block that uses/relies on them. In your code snippet,


Code
sub whatever { 
my ($string, @array, %hash);
for (my $x = 1; $x < 1000; $x++) {
my $temp = 0;
#etc...
}
}

$string, @array and %hash aren't being used. But assuming that you'll be using these 3 variables only within the whatever sub, where you declared them is perfect. Perl's garbage collection system will destroy these variables after the whatever sub terminates.

However, if you're using $string, @array and %hash only inside the for loop, use this instead:


Code
sub whatever { 
for (my $x = 1; $x < 1000; $x++) {
my ($string, @array, %hash);
my $temp = 0;
#etc...
}
}

Hope this helps!


 
 


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

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