in reply to Re^2: Understanding variable scope in perl
in thread Understanding variable scope in perl

sorry, I just came from class. when I add 'use strict', perl throws a lot of compilation errors asserting that almost all of my global symbols require explicit package naming. I guess it means that I need to prefix everything with main::, no?
  • Comment on Re^3: Understanding variable scope in perl

Replies are listed 'Best First'.
Re^4: Understanding variable scope in perl
by liverpole (Monsignor) on Sep 29, 2005 at 23:37 UTC
    No worries!

    Actually, no, you don't need to prefix everything with "main::", though that would certainly be one way to go about it.

    Better to make global only the few things that you really want to have global, by putting them at the top of your program, and prefixing them with my:

    # My global variables (Actually, these should really be constants...) my $boiling_point_fahrenheit = 212; my $known_other_universes = 0; my $answer_to_everything = 42;
    You should make everything else local (actually lexically-scoped) with my prefixing it.

    A good test of whether a given variable should be global or not:  if you were convert most or all of the subroutines in the program into separate packages, and import them to the main program as objects, would the variable be one that you'd like to retain in the main program (global!), or pass to the constructor or one of the methods of some object? (lexical!)

    So, go back and fix all of the errors that you get, and then let me know:  what kind of output do you get now??