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,
Ovid

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
in thread declare globally by Parham

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.