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

Re: Are global variables "bad"?

by JavaFan (Canon)
on Apr 21, 2009 at 20:01 UTC ( [id://759096]=note: print w/replies, xml ) Need Help??


in reply to Are global variables "bad"?

So, my question boils down to: is it a bad idea to have global variables?
There are several answers to your question. Let me just give a few remarks.
  • First of all, "global variables" is not a term everyone uses to mean the same thing. Many Perl programmers use the term "global variable" to mean "package variable". But in general, a "global variable" means a variable that's "visible" or "accessable" from everywhere. A lexical variable defined at the file scope can also be a global variable.
  • Perl 1, 2, 3 and 4 didn't have lexical variables. Or name spaces. All variables where global. Was Perl evil then? I don't think so.
  • "Global variables bad; non-global variables good" is an often chanted mantra, but it's an incorrect one. What is considered good programming is to have variables with a scope as small as needed. And that when you can use a lexical variable instead of a package variable, the lexical is usually preferred. Note that this does not mean every global variable is bad - it's not a rare occasion having a global variable that is appropriate.
  • Whether you use a global variable or not usually doesn't have much impact on speed. And if it does have much impact, it's often caused by passing large variables into subroutines in such a way that copying happens; if that's the case, globals may be a winner (although using references often reduces the need for copying as well).

Replies are listed 'Best First'.
Re^2: Are global variables "bad"?
by Anonymous Monk on Apr 21, 2009 at 20:34 UTC
    "Perl 1, 2, 3 and 4 didn't have lexical variables. Or name spaces. All variables where global"
    Where did the local statement fit into this absolutist scheme?
        local only works on global variables.
        Not true. It's not even true if you meant "package" where you wrote "global".
        $ perl -wE 'my @a = (1, 2, 3); {local $a[1] = 7; say "@a";} say "@a"' 1 7 3 1 2 3
      local() essentially replaces the current variable (package variable - or aggregate element) with another variable, until the runtime exits the scope the local() is in.

      If no magic is involved, it may be easier to think of it as temporary replacing the value.

Log In?
Username:
Password:

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

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

    No recent polls found