[EMAIL PROTECTED] wrote:
I see. Thanks Shawn. Since we are at it, would you mind explaining a little bit
about the significance of "our" keyword. I have never understood it properly.
Most books that I referred to say that it's a "lexically-scoped global
variable". What does that mean? I understand global variables to be the ones
which are accessible to all perl program units (modules, packages or scripts).
But then, what is so lexically-scoped about it? What do the perl compiler and
opcode interpreter do when encounter a variable name prefixed by "our"?

Below are three files, main, foo.pm, and bar.pm. These show the way 'my' and 'our' behave.

A 'my' global variable is scoped only to the file it is in. It hides any 'our' variable (of the same name); you can only access the 'my' variable. 'our' variables are global globals; they are the same and accessible across files.

Below, you will note that the sub super_bar uses 'our' (in a block) to override the 'my' definition of $Self to access the 'our' one. With practice, you too can create code that is a nightmare for your maintainers.


#!/usr/bin/perl

use strict;
use warnings;

our $Self = __FILE__;

use foo;
use bar;

print "main: $Self\n";
foo();
bar();
super_bar();

__END__


# foo.pm

our $Self = __FILE__;
print "foo: $Self\n";

sub foo {
  print "foo: $Self\n";
}

1;
__END__


# bar.pm

my $Self = __FILE__;
print "bar: $Self\n";

sub bar {
  print "bar: $Self\n";
}

sub super_bar {
  our $Self;
  print "super_bar: $Self\n";
}

1;
__END__



--

Just my 0.00000002 million dollars worth,
   --- Shawn

"Probability is now one. Any problems that are left are your own."
   SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to