develooper Front page | perl.perl5.porters | Postings from August 2001

'can' with undefined subs

Thread Next
Tony Bowden
August 16, 2001 16:02
'can' with undefined subs
Message ID:

A weird question came up on the ScriptScape that seems to have surprised
quite a few people: if you have a sub that has been forwards declared,
but never actually defined, what does 'can' return?


package Foo;
sub bar;

package main;
my $ref = Foo->can('bar');
  # what is $ref?

Dominus thought it would return false.  Damian thought it would return
true, but not actually be a coderef.  However, it does returns a coderef,
which barfs if you then call it ...

... except ...

There's a semi-common idiom where you do this when you know you want to
trap this method with your AUTOLOAD, and don't want dispatch to keep
searching the @ISA tree.

So, if we add an AUTOLOAD to Foo, calling the coderef returned from can
does the right thing.

Is this behaviour 'correct'? It's somewhat useful from an end-user's
point of view, as it enables 
  if (my $ref = Foo->can('bar')) {
to work as expected, if there's an AUTOLOAD that does the right thing,
but it will equally trip the user up if there isn't an AUTOLOAD and the
method they thought they were safe in calling explodes.

It also doesn't seem to be documented anywhere.

 Tony Bowden | |
all history is too small for even me; for me and you,exceedingly too small

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About