in reply to Re: Re: Re: Re: Re: Re: VarStructor 1.0
in thread VarStructor 1.0

You describe your problem as :

Each new loop that I wrapped the original code in required resetting some variables, which I was able to handle, but then I added another loop, to make a single instance of the script run over and over for different clients. Once one job is done, it waits for another request. I could have tried figuring out what variables needed to be cleared, but I could easily have missed something.

This is exactly the problem that block scoped ("lexical") variables, that is, variables declared with my solve for you:

use strict; my @sites = qw(http://www.corion.net); my $user_name = "Corion"; for my $user_site (@sites) { print "Summary for site $user_site\n"; my $link_number; # = 0; # left the initialization out intentionally for my $link (get_site_links($user_site)) { print "$link_number: Found link $user_site$link\n"; $link_number++; }; }; sub get_site_links { return qw(index.html test.html error.html); };

Here, there is no need to reset the variables outside of their usage, as they won't be available, and for example $link_number will be reset to zero by Perl every time a new site loop is started. use strict; is there so that Perl can check for me whether I've used any of my block scoped variables only within the block I've intended to use them.

So, Perl already provides you with the tools, but you also have to use the right tool for the right problem...

Another, less good solution for your problem might be the local keyword, which allows you to temporarily assign a different value to a variable and Perl automagically restores the previous value when you leave the block of the local declaration, but for the problem you specified, lexical variables are the best solution.

Replies are listed 'Best First'.
A reply falls below the community's threshold of quality. You may see it by logging in.