Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

What is the purpose of using our and when do I use it instead of local or my?

Replies are listed 'Best First'.
Re: Usage of our
by Beatnik (Parson) on May 21, 2001 at 10:42 UTC

      I understand the usage of local and  my.
      But can anyone explain what's "a variable global within the current block" and when do you want to do that?

        Imagine you had a package:
        package MyPack; my $a;
        As defined above, there is no way for anything outside the scope of MyPack to access $a. Of course, with Exporter and a few other standard class tricks, this is not hard to fix, but using Exporter for every class is a nuicence.

        Using 'our' makes the variable known at the global scope level (that is, everyone can access it now):

        package MyPack; our $a;
        Anywhere outside of MyPack, I can now get the value of $a via the variable $MyPack::a.

        So 'our' can be considered to be declaring which variables are public in a object-oriented sense. It mostly replaces the functionality of Exporter which can be awkward to use.


        Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
(tye)Re: Usage of our
by tye (Sage) on May 21, 2001 at 21:21 UTC

    Never. (: Use use vars when you need a package global, such as a variable you plan to export. This is the same case when you might want to use our but doing so just makes your code less portable. If you aren't writing a module, then my is what you should use nearly all of the time. See other response for more information on some of the exceptions.

            - tye (but my friends call me "Tye")
Re: Usage of our
by tachyon (Chancellor) on May 22, 2001 at 12:40 UTC
    For an indepth analysis of this look no further than the pages of the the one and only M-J. Dominus. Short answer (stolen from MJD) 'Always use my, never use local.' To learn about namespaces my/our/local see: Coping with Scoping http://perl.plover.com/FAQs/Namespaces.html In this next article MJD partially recants from the brief advice to never use local, always use my Seven Useful Uses of local http://perl.plover.com/local.html Hope this helps, I found these articles very useful Cheers tachyon my $answer =[q;7566626f206f7420756f7920656d6f636c65772049;]; print join''=>reverse split''=>pack H42=>$answer->[0]=>eval;
Re: Usage of our
by John M. Dlugosz (Monsignor) on May 21, 2001 at 23:47 UTC
    I answered you in the Categories Q&A section.

    (there is no section for "modules" so I put it under subs, since the my/local was there.)

    —John