laziness, impatience, and hubris | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
There are basically four ways of declaring a global variable (well, I could some up with some others using soft references, but they're bad juju). 1: $global::variable; 2: no strict 'vars'; $variable; 3: our $variable; 4: use vars qw/$variable/; Of the three, the first should not be encouraged as it's easy to misspell the global and strict won't tell you that. This makes your program more likely to be buggy. The second is terrible because you lose all benefits of strict, even with lexically scoped variables (misspelling the lexically scoped variable means Perl will think it's a global). The third is new, as of Perl 5.6. It allows you to declare a lexically scoped global variable. If that sounds confusing, good. If you lexically scope your globals, it can become confusing if you use the same name outside of the scope because then it's easy to misunderstand whether or not something is global. The "use vars" pragma is the cleanest, IMHO. You can declare it as global, it's not lexically scoped, and when you run across it later in your program, you know it's a global, no questions asked. All of the above information aside, using global variables can be very dangerous because they are more difficult to manage. As a side note, the first method is the only one (of the four that I present) that allows you to declare a global in another package. That's might be acceptable if you're exporting a global that a person asks for in their program, but it's usually bad programming to mess with someone else's namespace. Cheers, Join the Perlmonks Setiathome Group or just click on the the link and check out our stats. In reply to (Ovid) Re: declare globally
by Ovid
|
|