|Think about Loose Coupling|
A better mod (%) operator?by BrowserUk (Pope)
|on Jul 08, 2002 at 20:44 UTC||Need Help??|
BrowserUk has asked for the
wisdom of the Perl Monks concerning the following question:
One thing I have always wanted (in every language I've used except assembler) is a function that returned both result and remainder of an integer division.
Both are usually calculated and left in seperate cpu registers after a DIV instruction, but I am forced by to use "/" and "%" to get at them, which means that the division is being done twice.
I did once create a function using in-line assembler in C to do this, but the single return value from a C function meant that the function was messy to use.
Perl's natural ability to return a list and assign lists mean that the idea resurrected itself in my brain when I saw this post and the answers to it.
My solution to this was:
Which I think is rather elegant, but still possible less efficient than the other solutions, and less efficient than it could be as I am still performing the division twice to get at the information.
I took a look at the inline-c stuff, but that doesn't help for the same reasons.
I also took a quick look at the overloading capabilities but I am not familiar enough with Perl to understand that yet.
I am wondering if it is possible to define a new operator for Perl? Maybe "/%" that would do the same thing as my div_mod() sub in the code above but accessing the appropriate registers to save a division?
Possibly better (and more Perlish) would be to have both values returned only if the mod (%) operator was called in a LIST context, especially as mod (%) is an inherently integer operator?
Does this have any merit? If so, would this have to be done deep in the guts of the compiler/interpreter or could it be added as a module in some way?