Sam Brightman Sam Brightman - 9 days ago 5
Perl Question

Take a reference to a Perl operator

In Perl, is it possible to take a sub reference to an operator (e.g.

eq
or
gt
)? Or is it not possible because they are not subs? I'd like to avoid redefining operators as subs where a comparison function is required.

I'm applying a checking function to config values, where the checker depends on the config key. One such checker is "compare to another key's value". The compare function can be defined via anonymous sub, or a named sub can be implement for each comparison type, but I think it's nicer to be able to say
compare_to("OTHER_KEY", \&eq)
.

EDIT: since one commentator wanted context and someone else voted to close as "too broad", I'll be absolutely clear that the question is not "how to write a config checker". This is only about taking references to operators: is it possible or not, what caveats apply?

Answer

Comparisons like eq and gt fall under a special category of the CORE functions where you can't create references to them. This is detailed in the documentation here http://perldoc.perl.org/CORE.html

So it looks like you can't do what you want to. I think you're options include:

  • Use anonymous subs or named subs to wrap the comparator you want to use
  • Passing in the string 'eq' and doing an if in compare_to and calling your comparator there.
  • You could do what some other languages do and make the second argument 1, 0, or -1 and take that to stand for gt, eq, lt, then if the value is a coderef, call that.
  • There might be a psuedo-magic way to approach this using AUTOLOAD if you are interested in going down that route.
Comments