simone
simone

Reputation: 5221

How can I tell if an object has a specific overloaded method?

I want to check if an object has a specific overload method in perl - for example if it has a sub dereferencing overload that would have been defined like this:

use overload
    '&{}' => \&_some_sub;

sub some_sub {...}

If I dump the symbol table of the package that created the object in question I see the following:

[
  "new",
  "import",
  "((",
  "(&{}",
  "ISA",
  "__ANON__",
  "BEGIN",
]

Does finding (&{} in the symbol table always mean that a sub deref methd exists? and does it work for other overloads too (I see ("" if I overload stringification).

Upvotes: 5

Views: 104

Answers (1)

Shawn
Shawn

Reputation: 52336

The details of how overload works under the hood isn't documented very well, and the first line of the IMPLEMENTATION section is What follows is subject to change RSN. So you can't depend on checking the symbol table.

The module does, however, provide a way to see if an operator is overloaded for an object:

overload::Method(obj,op)

Returns undef or a reference to the method that implements op.

So you can use

if (overload::Method($someobj, '&{}')) {
    # Overloaded sub deref
}

Upvotes: 6

Related Questions