[sf-perl] oddity with an exported and localized variable

Joe Brenner doom at kzsu.stanford.edu
Tue Dec 1 12:06:36 PST 2009

David Lowe <j.david.lowe at gmail.com> wrote:

> Joe et al. -
> Joe Brenner <doom at kzsu.stanford.edu> wrote:

> > The point here is that the exported sub appears to be
> > seeing the value the variable was assigned in the module,
> > rather than seeing the current value assigned in the script.
> > This isn't the way dynamic scoping is supposed to work,
> > correct?  Any ideas what might be going on here?
> This surprising behavior is documented in 'perldoc perlmod':
> http://perldoc.perl.org/perlmod.html#Symbol-Tables
> The fix is to change both the export and import lists to
> '*exported_variable' instead of '$exported_variable'; making these
> changes causes the example code to behave as expected.

Quite right! It is, indeed, documented there in "perlmod"... (but
not, for example, in "Exporter"):

  What makes all of this important is that the Exporter module uses
  glob aliasing as the import/export mechanism. Whether or not you
  can properly localize a variable that has been exported from a
  module depends on how it was exported:

   1. @EXPORT = qw($FOO); # Usual form, can't be localized
   2. @EXPORT = qw(*FOO); # Can be localized

> The bug, IMO, is that neither the documentation for 'Exporter' nor
> 'local' mention it. OTOH the documentation for Exporter *does* say
> (paraphrasing) "DO NOT EXPORT VARIABLES"... and the documentation for
> 'local' *does* say (paraphrasing) "DO NOT USE LOCAL EXCEPT FOR MAGIC
> PUNCTUATION VARIABLES"... so there's a bit of poetic justice at work
> here, too ;)

Yes, obviously you only hit this feature-bug if you're doing *two*
things that would now usually, be regarded as poor style, and I
didn't mean to suggest that writing code like this is a good idea.
But on the other hand, these features *do* exist, and really are
supposed to work and even, "do what I mean".  And you might even
turn up an odd case where it makes sense to do things like this.

More information about the SanFrancisco-pm mailing list