GYAH! No, don't do that. It'll be clearer for the first week or so, then you'll need extra comments to figure out where that hash is coming from. Then you'll make a few changes, and forget to update the comments. (Trust me, you will forget.) Then you'll want to process many widgets instead of just one, so your hash will become an array of hashrefs, and you're totally screwed.

Globals are good for things like program options (i.e. don't pass around the args hash you got back from Getopt). Globals are good for collecting the data you're operating on: if you're modelling TCP connections, then a global array of connection objects is perfectly reasonable. Globals are sometimes reasonable for the outermost scope of your problem space. If you're writing a state machine, for instance, and you know somehow that you'll never want to model more than one state machine, then it's sometimes okay to put your state in the global namespace rather than packaging it up into a class (or even a hash) and accessing it opaquely.

Most of the time, though, the little time you save by making stuff global rather than packaging it up just a little bit is completely overwhelmed by the time it takes you to refactor your code when your problem expands, even if you're just prototyping something. Slinging around globals is false laziness.

(Anyone else want the soapbox? :-)

--
:wq

In reply to Re(2): Is this a good approach for reducing number of global variables? by FoxtrotUniform
in thread Is this a good approach for reducing number of global variables? by ybiC

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.