Syntactic Confectionery Delight | |
PerlMonks |
Re: Help needed understanding global variables in Perlby Sinister (Friar) |
on Mar 05, 2002 at 09:12 UTC ( [id://149306]=note: print w/replies, xml ) | Need Help?? |
Mmmm... First of all: Global variables are not the best thing man has ever invented. It is better to have your routines talk to each other by what they return, then trough the use of global variables. (loose coupling) But, sometimes, we do need globals. In that case, if you have read the perldoc on our (do `perldoc -f our` on your $SHELL) you'll notice, that with our you can create a variable that goes beyond even package scope. In that case you would never want to use our inside a routine, because you would like the routine data to be private to that routine. eg:
Would actualy print " world", since $foo is routine scope and $bar is lexical scope. Defining a global variable would require you to do: my $foo in the main scope of a 'package'. eg:
This will actualy print "hello world" - which would have worked perfectly if you had choosen to do my $bar = ""; instead of our. Now to get back on the difference between our and use vars NOTE: The functionality provided by this pragma has been superseded by "our" declarations, available in Perl v5.6.0 or later. See the our entry in the perlfunc manpage. These lines come directly from the documentation of vars itself. I hope this has answered some of your questions. A righthanded-lefthand.... "Field experience is something you don't get until just after you need it."
In Section
Seekers of Perl Wisdom
|
|