First I'll tell you why global variables are Bad; then I'll explain how to get yourself into trouble if you so choose.

Global variables are one of the most common sources of bugs in code. Worse, once they're in there, global variables are hard to stamp out, and the bugs they cause are difficult to trace. Here's an example:

my $name = 'Jean ValJean'; my $number = 24601; steal_candlesticks(); become_mayor(); print "Who am I? $name, $number!\n"; sub become_mayor { if ($number == 1138) { do_thx(); } if ($number == 6) { do_prisoner(); } print "I am the mayor of this town\n"; } sub steal_candlesticks { if ($number = 1138) { do_thx(); } print "Took the candles, took my flight\n"; } sub do_thx { $name = 'THX'; } sub do_prisoner { undef $name; }

The person that wrote this code expected the last line to print "Who am I? Jean ValJean, 24601!" Instead, we got "Who am I? THX, 1138!" And unfortunately, the bug is not easy to trace. Imagine if I had added flee_javair(), adopt_cosette(), etc., etc. The bug (which is in the if-statement for steal_candlesticks()) could be anywhere that $number is referenced... and there's no easy way to find it.

You may be wondering why one would make so much fuss over a small program. The first reason is that useful programs tend to grow over time. Since we always hope that we're writing useful programs, we should always be prepared to wake up one morning to discover that our small CGI program has become gigantic. The second reason is that global variables become a hard habit to break once you're used to them. It's always best to start good habits as soon as possible.

"So what do I do instead?" Glad you asked. The best way to get variables out of a subroutine is to return them from a subroutine. If you want to return two or three, you can simply return a list:

sub who_am_i { my $name = 'Jean ValJean'; my $number = 24601; return ($name, $number); } # Chose different names here to emphasize that # these are different variables, but could # have chosen $name and $number again my ($prisoner_name, $prisoner_number) = who_am_i();

Finally, here's the part where I tell you how to completely disregard all that I've been saying. (Several people have no doubt done so while I've been typing. :) )The my keyword is used to declare local variables. In other words, they're only visible in the subroutine (or other block) you declared them in.

If you're using 5.6+, though, you can declare variables visible to the entire file using our. (If you're not, see use vars.) These are the globals you're looking for.

Note: Code is not tested, and I still can't hit the high tenor notes in Les Miz.


Update: Fixed typos, and for some reason I had the link to "our" labeled "my".

In reply to Re: Setting Global Variable in Sub by stephen
in thread Setting Global Variable in Sub by Zombie ss

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, 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, 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.