Please excuse me if this has been answered elsewhere.

What nature of magic causes this code...

#!/usr/local/bin/perl -w use strict; use Data::Dumper; my $x = bless {}, 'Foo'; print Dumper(\%Foo::); $x->import(qw(:blah foo whatever 123)); print Dumper(\%Foo::); $x->almost_any_method_besides_import(qw(:blah foo whatever 123)); print Dumper(\%Foo::);

...to output the following:

$VAR1 = {}; $VAR1 = { 'import' => *Foo::import }; Can't locate object method "almost_any_method_besides_import" via pack +age "Foo"\ at test.pl line 9.
According to all the perldoc I can find, import isn't special: it's just a class method of your class, which may or may not exist. And "use" doesn't care if it doesn't exist. (I notice that the pod at perlmonks.com says use doesn't raise an error if import doesn't exist, but my pod says use doesn't call import if it doesn't exist.)

However, the test above demonstrates that independant of use, trying to call method import which doesn't exist is handled differently than with almost any other method ("almost" only because I'm not 100% sure there is no other similar case... I don't know of any offhand, however).

I'd expect the above code to bomb on the $x->import line with an error message similar to the one shown for the second method call. Instead, it creates an import method in package Foo. Not only that, but the method does nothing instead of bombing because the things I'm trying to import don't exist.

Not only that, but use strict and warnings don't have anything to say on the matter either.

I have no problem with the fact that there's magic here, but I'd like to know what the magic is and where it's documented, to train myself that this is actually predictable :)

Thanks,

Alan


In reply to import() magic by ferrency

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.