如何检查是否使用对象调用方法调用了子程序

How to check if a subroutine was called with an object invocation method or not

您可以使用下面示例中的两种语法调用子例程作为方法。

但您也可以不将其作为对象调用。

#====================================================
package Opa;
sub opa{
    $first= shift;
    $second= shift;
    print "Opa $first -- $second\n";
}

package main;
# as object:
Opa->opa("uno");
opa Opa ("uno");
# not as object
Opa::opa("uno","segundo");
Opa::opa("Opa","uno");
#====================================================

有没有办法从子例程内部知道"in general",子例程收到了什么样的调用?

您可以使用 Devel::Caller 中的 called_as_method

use Devel::Caller qw( called_as_method );
sub opa{
    print called_as_method(0) ? 'object: ' : 'class: ';
    $first= shift;
    $second= shift;
    print "Opa $first -- $second\n";
}

输出:

object: Opa Opa -- uno
object: Opa Opa -- uno
class: Opa uno -- segundo
class: Opa Opa -- uno

您也可以使用 ref() 函数而不是使用外部模块来执行此操作:

use warnings;
use strict;

package Test;

sub new {
    return bless {}, shift;
}
sub blah {
    if (ref $_[0]){
        print "method call\n";
    }
    else {
        print "class call\n";
    }
}

package main;

my $obj = Test->new;

$obj->blah;
Test::blah;

输出:

method call
class call