I’m looking at some older Perl code on Perl Monks to figure out programming with Win32::OLE and MS Word. Scattered throughout the code are variables with names like $MS::Word and the like, without a ‘my‘ included in their declaration. After reading a bit on Google, I understand that these are called ‘package variables’ versus ‘lexical variables’ declared using my.
My first question is ‘What are package variables good for?‘. I (think) I understand what lexical variables are, but I don’t understand the purpose of package variables or how their use differs from lexicals, so my second question would be, ‘What is the difference between lexical and package variables?‘
A package variable lives in a symbol table, so given its name, it’s possible to read or modify it from any other package or scope. A lexical variable’s scope is determined by the program text. The section “Private Variables via my()” in the perlsub manpage gives more detail about defining lexicals.
Say we have the following
MyModule.pm:Notice that it contains a package
$callsand a lexical$calls. Anyone can get to the former, but the module controls access to the latter:The program’s output is
As you can see, package variables are globals, so all the usual gotchas and advice against apply. Unless explicitly provided access, it’s impossible for code outside the MyModule package to access its lexical
$calls.The rule of thumb is you very nearly always want to use lexicals. Perl Best Practices by Damian Conway is direct: “Never make variables part of a module’s interface” (emphasis in original).