use strict; #<--**** use warnings; #<---***

Declaring global variables using fully qualified names:

$main::x = 10; print $main::x, "\n"; #10

Above okay under use strict.

Declaring global variables with use vars:

use vars qw{$x}; print $x, "\n"; #10

'use vars' provides a shortcut: you don't need to use the fully qualified variable name, which is what use strict requires.

Declaring global variables with our:

# $y = 'hello'; #error under use strict our $y = 'hello'; print $y, "\n"; #hello

Once again, our provides a shortcut to having to use fully qualified names under use strict.

What's the difference between our and use vars?

{ our $z = 5; print $z, "\n"; #5 } # print $z, "\n"; #error print $main::z, "\n"; #5 { use vars qw{$s}; $s = 'bye'; print $s, "\n"; #bye } print $s, "\n"; #bye

'use vars' has file scope, i.e. it applies to the whole file, and cannot be undone (e.g. with 'no use vars')--while our has block scope, so the short form of the variable name only works within the same block as the our statement.

Note that the global variable always exists no matter what method you use--the issue is whether you can refer to the global variable using the short form of the variable name or not.


In reply to Re: to "use vars" or not to by 7stud
in thread to "use vars" or not to by westy032001

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.