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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.