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

Hi, I want to define a new perl operator (not overload an existing one) such as "<--". How can I define it and use it in my script? The reason I choose to use operator not function for the this expression is that it make more sense visually to use an operator. Thanks in advance.

Replies are listed 'Best First'.
Re: Define an operator in perl 5.6
by theorbtwo (Prior) on Feb 12, 2002 at 23:54 UTC

    Simple answer: You can't. You can't define an operator (like a op b) at all, you can only define functions (like f(a,b)). Functions are sometimes called list operators (mostly because you can call them without parens), but I think doing that confuses the issue. Moreover, you can only define functions that fit in a limited namespace: /^A-Za-z_A-Za-z_0-9+$/ (you might be able to get around this with symref magic... but I wouldn't recommend trying).

    Complicated answer: you can use source filters to do arbitrary transforms on your code before perl compiles it. See Filter::Simple. While this can certianly do what you want (assuming what you want to do is possible), it's almost certianly really difficult. (Best-case scenario is that you can crib off of Switch or somthing similar.)


    We are using here a powerful strategy of synthesis: wishful thinking. -- The Wizard Book

Re: Define an operator in perl 5.6
by Anonymous Monk on Feb 13, 2002 at 04:33 UTC
    weel, see perlhack, hack the source, recompile, have your new operator ;) (I can't possibly conceive why you would need a custom one)