Here's an option that uses Roy's scoping block and your possibly lengthy list of global variables.
You create a hash reference inside the scoping block: it is not visible to any code outside the block including any subroutines (one of the main problems with globals). You then let Perl autovivify your $response, $var2, etc. as keys in the hashref: all of these will go out-of-scope with the hashref (sorry, that's probably obvious).
You can pass the hashref to subroutines that need any of the global variables: that's good for (a) performance because you're only passing a single scalar and (b) good for maintenance because you don't need to align lengthy lists of arguments between caller and callee. Furthermore, because it's a reference you don't need to return it.
The only cautionary note I'd raise is don't trap the hashref in a closure: that will have a high probability of causing you grief.
Here's a fragmented example:
#!/usr/bin/perl ... { # scoping block my $rh_vars = {}; if (...) { $rh_vars->{response} = 'whatever'; if (...) { $rh_vars->{var2} = 'something'; } func($rh_vars); } print $rh_vars->{response}; } # $rh_vars out-of-scope here ... exit 0; sub func { my $rh_vars = shift; if (exists $rh_vars->{var2}) { # do something with "var2" } }
I've kept this example code short and skeletal. I'll happily expand or clarify any points if necessary.
As an aside, you may notice that this code is halfway down the road to being object-oriented: you've encapsulated and hidden your data in the hashref which is acting like a light-weight object (unblessed - no inheritance).
PN5
In reply to Re: Re: Re: Best way to pass variables?
by Prior Nacre V
in thread Best way to pass variables?
by Elijah
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |