Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

'can' operator?

by pg (Canon)
on Nov 18, 2002 at 18:00 UTC ( [id://213832]=perlquestion: print w/replies, xml ) Need Help??

pg has asked for the wisdom of the Perl Monks concerning the following question:

I was wondering about something. I can check whether a class has a certain method, by calling can, for example,
use Math::Complex; print "plus is supported\n" if (Math::Complex->can("plus"));
It works. I checked the Math::Complex module, the overloaded “+” actually calls this 'plus' function. Now, is it not normal for me to expect that, the following should work?
use Math::Complex; print "+ is supported\n" if (Math::Complex->can("+"));
But it does not, even though “+” is overloaded for this class. My question is:
  1. Did I do something wrong? If yes, then what is the correct syntax to check whether an operator is overloaded?
  2. If I didn’t do anything wrong, is it not nice for Perl to support a unified interface for checking whether a method, or operator is supported? They are both operations you can apply on a class/object though. Also, you remember those operators by their symbols, for example "+", not by the methods under, for example, if I didn't check the Complex.pm, how can I know that "+" is actually "plus"?

Replies are listed 'Best First'.
Re: 'can' operator?
by broquaint (Abbot) on Nov 18, 2002 at 18:14 UTC
    Did I do something wrong? If yes, then what is the correct syntax to check whether an operator is overloaded?
    Yes, can only checks whether a given class/object implements a method, not whether operators overloaded. For that you'll want overload::Method from the overload module.
    HTH

    _________
    broquaint

Re: 'can' operator?
by Zaxo (Archbishop) on Nov 18, 2002 at 20:33 UTC

    The overload pragmatic provides a couple of functions you can use for that.

    • overload::Overloaded('$foo+1') takes a perl expression as a string and tells you whether any of its operators are overloaded in the context of that expression.
    • overload::Method($obj,'+') returns a code reference to the method overloading '+' for $obj, or undef if not overloaded.

    After Compline,
    Zaxo

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://213832]
Approved by TStanley
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-04-19 22:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found