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

'can' with undefined subs

Thread Next
From:
Tony Bowden
Date:
August 16, 2001 16:02
Subject:
'can' with undefined subs
Message ID:
20010817000224.A20755@blackstar.co.uk

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?

i.e.

package Foo;
sub bar;
1;

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')) {
    $ref->();
  }
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
-- 
--------------------------------------------------------------------------
 Tony Bowden | tony@tmtm.com | http://www.tmtm.com/
all history is too small for even me; for me and you,exceedingly too small
--------------------------------------------------------------------------

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