3

I would like to know if it is possible to call a method from an object without passing the self argument.

As an example, I have a package:

package MyPackage;

sub new {
    my $class = shift;
    return bless {}, $class;
}

sub test {
    print("called(" . join(', ', @_) . ")\n");
}

From a script, I call the constructor and then the test method:

my $obj = MyPackage->new();
$obj->test("str");

giving me the following output:

called(MyPackage=HASH(0x55b05d481f48), str)

Is there any way (even if it's not a best practice or use some "arcane" features of the language) to call the test method using only the reference $obj without having the "self"-parameter passed implicitly.

In a word, is it possible to do something like this:

$objXXXXtest("str");

with XXXX the hypothetical construct and get called(str) as output?

2 Answers2

8

It's a little unorthodox, but UNIVERSAL::can returns a code reference that you could call without the referent.

$obj->can("test")->("str");
mob
  • 117,087
  • 18
  • 149
  • 283
0

You would just call the function directly, and not as a method of an object:

myPackage::test("str");
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Yes, it would be the "normal way" to do it, but I'm only provided the `$obj` reference and I don't know the class of the object. – Henri Mirton Aug 26 '18 at 15:07