develooper Front page | perl.perl5.porters | Postings from October 2003

[PATCH] Fixing UNIVERSAL.pm's bit of unpleasantness

Thread Next
From:
schwern
Date:
October 6, 2003 13:15
Subject:
[PATCH] Fixing UNIVERSAL.pm's bit of unpleasantness
Message ID:
20031006131436.G20960@ttul.org
I don't know why I didn't think of this before!  I don't know how many times
this has bitten me in the ass.

Now, if we wanted to be 100% correct it would be

    return unless $_[0]->isa(__PACKAGE__);

in case somebody subclasses UNIVERSAL and expects the imports to work, but
I didn't want to add the overhead and besides, nobody's insane enough to
do that (Bailiff, please restrain Abigail ;).

Interestingly, both of these produce false:

    Foo->can("import");

and

    use UNIVERSAL;
    Foo->can("import");

same with 'isa' and 'can'.  Does can() not count UNIVERSAL?  I don't see
any special case in universal.c.  Not that I'm complaining, mind you.  It
neatly avoids Yet Another Side Effect of loading UNIVERSAL.pm.


--- lib/UNIVERSAL.pm	2003/10/06 19:56:04	1.1
+++ lib/UNIVERSAL.pm	2003/10/06 20:01:54
@@ -9,9 +9,15 @@
 # Exporter.  It's bad enough that all classes have a import() method
 # whenever UNIVERSAL.pm is loaded.
 require Exporter;
-*import = \&Exporter::import;
 @EXPORT_OK = qw(isa can VERSION);
 
+# Make sure that even though the import method is called, it doesn't do
+# anything unless its called on UNIVERSAL
+sub import {
+    return unless $_[0] eq __PACKAGE__;
+    goto &Exporter::import;
+}
+
 1;
 __END__
 
--- t/op/universal.t	2003/10/06 20:00:42	1.1
+++ t/op/universal.t	2003/10/06 20:03:39
@@ -9,7 +9,7 @@
     $| = 1;
 }
 
-print "1..100\n";
+print "1..101\n";
 
 $a = {};
 bless $a, "Bob";
@@ -195,3 +195,9 @@
 my $x = {}; bless $x, 'X';
 test $x->isa('UNIVERSAL');
 test $x->isa('UNIVERSAL');
+
+
+# Check that the "historical accident" of UNIVERSAL having an import()
+# method doesn't effect anyone else.
+eval { Some::Package->import("bar") };
+test !$@;


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About