in reply to Examples fo Where "our" is really needed

I doubt that you will find any example in which our makes a huge difference.

So why bother having it at all? I suppose that the key idea behind our is to mitigate some of the dangers associated with global variables (when used in conjunction with strict). For instance, consider this case:

use strict; use vars '$x'; $x = 3; sub critical { my $w = 50; # my $x = 100; # oops: commented out by mistake # my $y = 200; my $y = 300; frobnicate( $w, $x, $y ); # that's the global $x in there! }
So, by a programming error the global value is now passing as a lexical. our offers a way to reduce the likelihood of such an error:
use strict; $MyModule::x = 3; # ... sub critical { my $w = 50; # my $x = 100; # oops: commented out by mistake # my $y = 200; my $y = 300; frobnicate( $w, $x, $y ); # won't compile }
...but you can still turn off the qualification requirement selectively:
sub that_uses_global_x_heavily { our $x; # we drop the formalities locally foobar( $x ); # ... $x = tweak( $x ); # ... and_one_more_thing( $x ); # ... }

Of course, there are other ways to avoid the errors that this scheme is trying to prevent, starting with using very different naming conventions for globals and lexicals.

So, bottom line, if you believe that (1) globals that are "easily accessible" (i.e. without the need for full qualification) from anywhere in the package are an invitation to difficult-to-detect bugs; and (2) fully qualified names are a pain, then our lets you have your cake and eat it too. Whether this capability was worth adding (along with the attendant confusion and pitfalls) would depend on how strongly you feel about (1) and (2).

the lowliest monk

Replies are listed 'Best First'.
Re^2: Examples fo Where "our" is really needed
by TimToady (Parson) on May 05, 2005 at 01:48 UTC
    Well, scope localization was not really the main issue, but a nice side benefit. The key point to our is that it is a single syntactic declaration for a single name, and as such, a location on which you can hang various extra modifiers controlling your view of that variable. That was envisioned from the start, though we're only just now getting there with Perl 5 "attributes" and Perl 6 "traits". In essence, the our declaration functions as a peg on which you can hang other declarations, which use vars could never do.