[Pdx-pm] fun with import()

Eric Wilhelm scratchcomputing at gmail.com
Sun Aug 6 11:04:05 PDT 2006

If any module anywhere does "use UNIVERSAL;" or "require UNIVERSAL", 
everyone automatically is using Exporter::import() unless they 
explicitly declared their own import sub.  Bug?

  $ perl -e 'package Bar; package Bah; Bar->import("foo")'
  (silent okayness)

  $ perl -e 'package Bar;
    package Bah; use UNIVERSAL; Bar->import("foo");'
  "foo" is not exported by the Bar module
  Can't continue after import errors at -e line 1

  $ perl -e 'package Bar; our $v = 2; our @EXPORT = qw($v);
    package Bah; use UNIVERSAL; Bar->import(qw($v)); print $v;'

  $ perl -e 'package Bar; our $v = 2; our @EXPORT = qw($v);
    package Bah; Bar->import(qw($v)); print $v;'

Seems to violate the "it's okay if you asked for it" thing.  Shouldn't 
UNIVERSAL.pm try a little harder? (e.g. import() does return unless 
$package eq "UNIVERSAL")

Bit of a weird case in that I had stubbed-out some use Foo (...) 
parameters before actually implementing them and meanwhile tried use a 
module with antlers which will remain unnamed.  Somewhere in one of the 
dependencies is "UNIVERSAL::require", which leads to "UNIVERSAL".  How 
did I find this?  I leveraged a hack mentioned in a recent meeting by 
pdx.pm's own chromatic:

    unshift @INC, sub {
      my $self = shift;
      print join('|', @_), "\n";
      print "  ", join('|', caller), "\n";
      print "  ", join('|', %UNIVERSAL::), "\n";
      print "\n";
  use Moose;

Anyway, the head-scratching and subsequent @INC-hacking was interesting.  
And, now we know that everybody gets Exporter's import() whether they 
want it or ask for it or not, so you can safely ignore the Exporter.pm 
documentation and just do:

  our @EXPORT_OK = qw(foo bar baz);

But wait, UNIVERSAL might get fixed at some point, so just in case, 
let's permanently install the breakage:

  BEGIN { require Exporter; *UNIVERSAL::import = \&Exporter::import; }

Maybe we should collect this sort of thing into Bork.pm and put it on 
CPAN (assuming it hasn't already been done.)  A pdx.pm project perhaps?

Moving pianos is dangerous.
Moving pianos are dangerous.
Buffalo buffalo buffalo buffalo buffalo buffalo buffalo.

More information about the Pdx-pm-list mailing list