How to check if a subroutine has been called using the object invocation method or not

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

But you can also call 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"); #==================================================== 

This is the way, from within the subroutine, to know, in general, what sub reception caused ?.

+5
source share
2 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 
+2
source

You can also do this with the ref() function instead of using external modules:

 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; 

Output:

 method call class call 
0
source

Source: https://habr.com/ru/post/1257961/


All Articles