In Perl, how can I determine if a subroutine has been called as a method?

Is there a way to determine if a subroutine is called as a method (using @ ISA sensing) or as a simple subroutine? Perhaps with some extension to the supercaller () module?

For example, given

package Ad::Hoc; sub func() { ... } 

How func() distinguishes between the following two calls:

 Ad::Hoc->func; # or $obj->func Ad::Hoc::func('Ad::Hoc'); # or func($obj) 

(I know the desire to do this is a likely indication of poor design β„’.)

+7
methods perl
source share
2 answers

See if Devel :: Caller helps. I changed the code to call func on the object and it seems to work on my Mac using perl 5.14.3 (and 5.24.0):

called_as_method($level)

called_as_method returns true if the subroutine at $level was called as a method.

 #!/usr/bin/env perl package Ad::Hoc; use strict; use warnings; use Devel::Caller qw( called_as_method ); sub func { printf "%s\n", called_as_method(0) ? 'method' : 'function'; return; } package main; use strict; use warnings; Ad::Hoc->func; Ad::Hoc::func(); 

Output:

  method
 function 
+10
source share
 package Ad::Hoc; sub foo { my $self = shift; if(ref($self) ne 'Ad::Hoc') { unshift @_, $self; undef $self; } if($self) { # I'm a method } else { # I'm a sub } } 
-2
source share

All Articles