On Fri, May 21, 2010 at 5:15 AM, Shlomi Fish <shlo...@iglu.org.il> wrote: > On Friday 21 May 2010 07:43:07 HACKER Nora wrote: >> I still have a (meta) question referring to your advice to set it up as >> a global variable: I read that "Global variables are bad [...] >> (http://perldoc.perl.org/perlfaq7.html) - so when is it ok to use global >> variables and when not? So far, I tried to use as many private variables >> as reasonable/possible, even if I had to pass them around between >> (sub-)functions, sometimes even between to "levels". > > What the FAQ seems to mean is that global *package-scope* variables are > usually bad - i.e the ones you declare using <<use vars (...)>> or <<our>>. > However, I was referring to doing <<my $mode = shift(@...)>> as a lexical > variable that is in the lexical "global" scope and is visible by several > subroutines. Such variables are not too bad (at least not in Perl) and if > you're looking for a cleaner solution, you can opt to define a class with > objects.
The short answer is that global state is accessible from anywhere. If you have a bug that is tied to global state then it could possibly exist anywhere in the application, which means that it could be very obscure and it might take you a long time to track it down. Compare that to sub-procedure arguments. You can clearly trace where the data came from and what influenced it so you can more easily find the bug. It's almost always possible to avoid using globals. Globals often appear to be the easier solution, but sometimes easier isn't always better. It would be "easier" to not "use strict" and "use warnings" too, but we do because they help us write better code. For an excellent talk about global state and why you should avoid it, please see this Google Tech Talk: 'The Clean Code Talks - "Global State and Singletons"' It can be found on YouTube at the following address: http://www.youtube.com/watch?v=-FRm3VPhseI The speaker relates it to the Java programming language and platform, but the advice applies to most, if not all, programming languages. -- Brandon McCaig <bamcc...@gmail.com> V zrna gur orfg jvgu jung V fnl. Vg qbrfa'g nyjnlf fbhaq gung jnl. Castopulence Software <http://www.castopulence.org/> <bamcc...@castopulence.org> -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/