gpt4 book ai didi

perl - 在 Perl 中,如何确定子例程是否作为方法调用?

转载 作者:行者123 更新时间:2023-12-04 11:39:28 24 4
gpt4 key购买 nike

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

例如,给定

package Ad::Hoc;

sub func() { ... }

怎么可能 func()区分以下两个调用:
Ad::Hoc->func;            # or $obj->func

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

(我知道,这样做的愿望可能表明设计不佳™。)

最佳答案

看看有没有Devel::Caller有帮助。我将代码更改为调用 func在一个对象上,它似乎可以在我的 Mac 上使用 perl 5.14.3(和 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();
输出:
方法
功能

关于perl - 在 Perl 中,如何确定子例程是否作为方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18217865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com