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

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?

Replies are listed 'Best First'.
Re: Re: Re: Re: Re: Usage of our
by Masem (Monsignor) on May 21, 2001 at 20:27 UTC
    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.

        Actually, that is not the case. Try it with a variable name other than $a or $b (which are exempt from explicit package qualification due to their usage in sort routines). Also, using my($a) wouldn't work because lexicals won't be available to the calling program. Lastly, your 'require Exporter' statement is unnecessary because you aren't exporting anything (for that you'd need to also set the @ISA array and one of the EXPORT arrays (or roll your own import() function).

        For further info see: perlman:perlmod and perlman:perlmodlib. You might also want to check out using the h2xs utility to create your module boilerplate.