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:
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; 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! }
...but you can still turn off the qualification requirement selectively: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 }
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 |