jg,

OoooOOhh ... not only the messy mindfield of globals -vs- proper scope but also the messy mindfield of where to define subroutines (at the top before an implicit main, or at the bottom after the implicit main). You should get lots of comments to this.

You should definetly minimize globals by using the my operator. Check out "Private variables via my()" section in perlsub. The thing to remember about using my is that A "my" declares the listed variables to be local (lexically) to the enclosing block, file, or "eval". So if you use my at the top of a package, all the methods/functions/subroutines defined after can have access to that lexical.

Now the big question is "is that a big deal?" I disagree with a lot of my fellow monks and feel it is not. demerphq has named this unintended globals but that would be only if you accessed the lexical in your methods. My fellow monks contend (and rightly so) that if you define your functions first and then your lexicals, perl will complain. I feel that's too big a price to pay over readability (but I've agreed to disagree about this point). My own opinion is to better know the code you're writing/maintaining and ensure you don't utilize file scoped lexicals (can anyone say code review).

Now when talking about packages, especially those which will be OO classes, the norm is to usually hang all the objects attributes off a blessed hash - your need for a package wide lexical is pretty small. Your need for true global variables is small also and should be kept to only those constructs which help with loading and inheritance (@ISA, @EXPORT, @EXPORT_OK).

-derby


In reply to Re: Whether to use local() by derby
in thread Whether to use local() by jerrygarciuh

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.