Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2024-04-25 08:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found