in reply to Re: Re: Usage of our
in thread Usage of our

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

Replies are listed 'Best First'.
Re: Re: Re: Re: Usage of our
by Anonymous Monk on May 21, 2001 at 17:25 UTC
    You can replace our with use vars.
Re: Re: Re: Re: Usage of our
by sierrathedog04 (Hermit) on May 21, 2001 at 20:25 UTC
    My program tempo2.pl is as follows:
    use strict; use MyPack; my $myString = $MyPack::a; print $myString;
    My module MyPack.pm can be either:
    package MyPack; require Exporter; $a = "Read from Mypack"
    or
    package MyPack; our $a = "Read from Mypack"
    The program tempo2.pl runs properly regardless of whether I use Exporter or 'our'. So my question is, when would one prefer the use of 'our' instead of Exporter?

    Is the use of 'our' in order to avoid possibly polluting a namespace by exporting all of the package variables?

      Yes, that's one considered use. If you know C++ or Java, then by using Exporter without restrictions, you may all your variables of your package public; this is usually not good OO programming practice. Using our specifies only which variables you want public, which is the better way to go.

      Also, to note: you should have "my $a = ..." in the Exporter example to keep everything strict.


      Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
        Actually, what I posted also passes use strict. If you insert 'use strict' into the Exporter example it passes even without using my() on $a.

        I think this is because 'strict' only barfs when there is neither an explicit package statement nor an explicit package identifier nor a lexical scope.

        Thus by explicitly declaring the package as MyPack I no longer need to say $MyPack::a.