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

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?

Replies are listed 'Best First'.
Re: Re: Re: Usage of our
by Masem (Monsignor) on May 21, 2001 at 15:32 UTC
    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
      You can replace our with use vars.
      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