in reply to Re^2: a global hash?
in thread a global hash?

Ways to achieve the desired goal:

  1. Global variables with our
  2. Make sure the subroutines that require access are all within the scope of the variable in question. In your posted code, this is the case. The my statement precedes your subroutine definitions and all are at the script level. This is what ikegami pointed out below.
  3. Explicitly pass the variable around. Makes it clear where it get modified, though it can make subroutine intent less clear and clutter code.
  4. Create an object/module to hold your variable - see perlboot, perltoot, perlobj... Any subroutine that uses the object will be able to access the package variable, though you may consider using getter and setters. Object oriented code is about as bad as bloated code gets, but tends to promote clarity in addition to Carpal_tunnel_syndrome. It also makes it explicit where you intended to interact with the globals, and if you use setters, you can insert breakpoints to easily track down some of those action at a distance bugs.
  5. Subroutines with closures to act as getter/setters without an explicit object/module. This starts getting risky for maintenance since some folks would consider this "clever".

Which option you choose depends on issues like how far separated the elements that need to access the value are logically, how concerned you are with code clarity, whether this is a one-off, whether this is getting distributed, how big the project is, etc. Just keep in mind that nearly every program has a life cycle that is completely different than you think it will be.

I'm sure this list is incomplete - anyone care to add some TIMTOWTDI? There's also providing the fully qualified package name on every access, but that has no benefit I can see over 1. and has some clear issues.