On Thu, Mar 26, 2009 at 14:05, Chap Harrison <c...@pobox.com> wrote:
snip
> This one baffles me.  I still have to explicitly export $g_database_path by
> putting it into @EXPORT - what is 'our' doing that 'my' doesn't?
snip

our and my both create variables.  The difference is their scope and their
interaction with packages.  my creates lexical variables that are visible
in the current scope and any nested scopes.  So

    #begin scope 0

    my $k = 10;

    # $i is not visible out here
    { #begin scope
        my $i = 5;
        #$i is visible;
        for my $j (0 .. $i) { #begin scope 2
            #$i is still visible
            func();
        } end scope 2
    } #end scope 1

    sub func { #begin scope 1
        # $i is not visible
        # but $k is because func was declared in its scope
    } #end scope 1

    #end scope 0

our variables create package (as opposed to lexical) variables.  Package
variables are visible throughout the package and can even be accessed from
other packages using the $PKGNAME::varname syntax.  our has two special,
and not obvious, properties:

1. it doesn't matter how many times you say our $var; $var is still
   the same variable (i.e. it is a singleton)
2. package variables are always visible when fully qualified (i.e.
   $PKGNAME::varname), but the short name is only visible to the scope
   that contained the our statement and any nested scopes

So

    #scope 0

    our $x = 5;

    { #scope 1
        our $y = 10;
        #$x and $y are visible
    } #end scope 1

    { #scope 1
        our $y;
        #$x and $y are visible and $y is 10
    } #end scope 1

    { #scope 1
        #$x is visible, but $y is not, but $main::y is and is 10
    } #end scope 1

Package variables are often used as global variables (as @EXPORT is).
Mostly because they are visible to other packages (when fully
qualified).

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to