PBP: 051 Lexical Variables

Global Variables; Just Say No.  Well, the PBP’s a little more lenient than that, and actually easier to follow by suggesting, “Avoid using non-lexical variables.” and admitting there are some times you just need a package or global variable.

I agree with the book; don’t clutter your global namespace and invite action at a distance if you don’t have to.  Keep your variables contained and your namespace clean, and your code will work better and be happier.

This is another case where “use strict;” is your friend.

There is a pretty useful table in the book of ways to avoid messing with a bunch of the punctuation variables.  Most of those ways are pretty painless and make your code more explicit.  Avoiding $` and $’ are particularly helpful, as it keeps regexes everywhere in the program more efficient.

If you do have to use Perl’s globals, localize changes as much as you can.  (I do find perlcritic to be a little overly picky here.  Yes, I know I’m not localizing changes to %ENV.  The whole POINT of what I’m doing is to change the actual environment.  Localizing that too far is hardly useful.  This is a place where the engineer knows best, and you just shut off that error for that block.)

Leave a Reply