in reply to Usage of our

our defines a variable global within the current block. our is new in perl 5.6.
on my and local: What is the difference between 'local' and 'my'?

Greetz
Beatnik
... Quidquid perl dictum sit, altum viditur.

Replies are listed 'Best First'.
Re: Re: Usage of our
by Anonymous Monk on May 21, 2001 at 11:30 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
        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?