in reply to Is this a good approach for reducing number of global variables?

I think that the use of globals increases as the program increases in size and complexity - it becomes simpler and sometimes clearer to pass half a dozen variables througha global hash than directly to the subroutine.

Perl gives us alot of power for quick hacks, simple tools, fast fixes. For example, returning the last thing evaluated, providing a default variable ( $_ ) for just about everything means I can construct, say, a script which changes every url in a couple of HTML files, in about five minutes. But most of those features are inappropriate for a program of any size where your spending days working on it anyway, the twenty minute time gain of using them isn't worth in terms of a lost of readability and reuse.

Cheers,
Erik
  • Comment on Re: Is this a good approach for reducing number of global variables?

Replies are listed 'Best First'.
Re(2): Is this a good approach for reducing number of global variables?
by FoxtrotUniform (Prior) on Mar 19, 2002 at 17:09 UTC

      I think that the use of globals increases as the program increases in size and complexity - it becomes simpler and sometimes clearer to pass half a dozen variables through a global hash than directly to the subroutine.

    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