Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

You can invoke a subroutine as a method using the two syntaxes in the example below.

But you can also invoke it not as an object.

#====================================================
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");
#====================================================

It there a way, from inside the subroutine, to know "in general", what kind of invocation a sub has received?.

like image 544
Diego Saravia Avatar asked Oct 10 '16 10:10

Diego Saravia


1 Answers

You can use called_as_method from Devel::Caller.

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";
}

Output:

object: Opa Opa -- uno
object: Opa Opa -- uno
class: Opa uno -- segundo
class: Opa Opa -- uno
like image 66
Chankey Pathak Avatar answered Sep 29 '22 19:09

Chankey Pathak