tunafish has asked for the wisdom of the Perl Monks concerning the following question:
I'm trying to write code to comply with Perl best practices, and I hear everywhere that global variables are evil and should not be used (and I'm even beginning to understand why!) However, I'm not sure what I should do in the following case.
I have a perl script that looks like this:
#!/usr/bin/perl use strict; require "lib.pl"; my $global_variable1='a'; my $global_variable2='b'; my $global_variable3='c'; switch(&subroutine1){ case 0: &subroutine2; case 1: &subroutine3; case 2: &subroutine4; }
The file lib.pl looks like this:
#!/usr/bin/perl use strict; sub subroutine1 { return rand(3); } sub subroutine2 { print $global_variable1; } sub subroutine3 { print $global_variable2; } sub subroutine4 { print $global_variable3; }
What this does, of course, is that Perl tells me that $global_variables 1-3 in the file lib.pl need an explicit package name and compilation fails.
What is the best practice way of doing this? The global variables in the original script are things like paths to various directories, database variables, etc. My question really is: How do I use globals without using globals?
Please explain things slowly, without using any big words, because I'm a Perl noob!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: What to use instead of global variables
by GrandFather (Saint) on Mar 28, 2012 at 06:21 UTC | |
|
Re: What to use instead of global variables (s/ / mal/)
by tye (Sage) on Mar 28, 2012 at 04:24 UTC | |
|
Re: What to use instead of global variables
by tobyink (Canon) on Mar 28, 2012 at 05:46 UTC | |
|
Re: What to use instead of global variables
by Cody Fendant (Hermit) on Mar 28, 2012 at 03:31 UTC | |
|
Re: What to use instead of global variables
by nemesdani (Friar) on Mar 28, 2012 at 04:30 UTC | |
by Cody Fendant (Hermit) on Mar 28, 2012 at 04:59 UTC | |
by eyepopslikeamosquito (Archbishop) on Mar 28, 2012 at 06:01 UTC | |
|
Re: What to use instead of global variables
by educated_foo (Vicar) on Mar 28, 2012 at 01:49 UTC | |
by Anonymous Monk on Mar 28, 2012 at 20:43 UTC |