在Perl中,如何确定是否将子例程作为方法调用? [英] In Perl, how can I determine if a subroutine was invoked as a method?

查看:57
本文介绍了在Perl中,如何确定是否将子例程作为方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以确定将子例程作为方法(使用@ISA探测)还是作为普通子例程调用?也许使用某种扩展模块super- caller()?

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()?

例如,给定

package Ad::Hoc;

sub func() { ... }

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

推荐答案

查看是否 Devel :: Caller 有帮助.我更改了代码以在对象上调用func,它似乎可以在Mac上的perl 5.14.3(和5.24.0)上运行:

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如果将$level处的子例程作为方法调用,则为true.

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();

输出:

method
function

这篇关于在Perl中,如何确定是否将子例程作为方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆