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!


In reply to What to use instead of global variables by tunafish

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.