PBP: 052 Package Variables

The PBP suggests avoiding package variables.  I almost can’t think of a reason to use one, so support this suggestion.

A package global is just that – a global.  You’re putting data in a place where it can be easily mucked with by anyone.  You’ve made that part of your exposed interface, and changing it will be difficult if you need to.

If you need to store data in your package, use a package-scoped lexical, a my variable at the top level of your package.  If people outside the package have to access it, provide an accessor function.

This gives you as the author control of how it’s accessed and what changes are made to it.  If you have to change how it’s stored or what it means, your accessor functions can translate back and forth from the new meaning to the old, without forcing every caller everywhere to change.  There’s lots of handy tools to write accessors, too.  There’s CPAN modules to help with this, but I now forget the names, having found Moo and Moose.

Why are you writing packages anyway?  Use Moo and make it an object; accessors are easy and obvious.

Leave a Reply