Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: to "use vars" or not to

by 7stud (Deacon)
on Nov 08, 2010 at 21:51 UTC ( [id://870204]=note: print w/replies, xml ) Need Help??


in reply to to "use vars" or not to

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://870204]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2024-04-20 02:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found