Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how can I determine if a subroutine was invoked as a method?

Tags:

methods

perl

Is there a way to determine whether a subroutine is invoked as a method (with @ISA probing) or as a plain subroutine? Perhaps with some sort of extension module super-caller()?

For example, given

package Ad::Hoc;

sub func() { ... }

How can func() discriminate between the following two invocations:

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™.)

like image 336
pilcrow Avatar asked Aug 13 '13 19:08

pilcrow


1 Answers

See if Devel::Caller helps. I changed the code to invoke func on an object and it seems to work on my Mac with 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
like image 192
Sinan Ünür Avatar answered Nov 06 '22 09:11

Sinan Ünür