perlmeditation
BrowserUk
<p>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.
<p>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.
<p> 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.
<p>Perl's natural ability to return a list and assign lists mean that the idea resurrected itself in my brain when I saw [id://180252|this post] and the answers to it.
<p>My solution to this was:
<p><code>
use strict;
sub div_mod { return int( $_[0]/$_[1]) , ($_[0] % $_[1]); }
my $i = 1332443;
my ( $s, $m, $h, $d );
($m,$s) = div_mod($i, 60);
($h,$m) = div_mod($m, 60);
($d,$h) = div_mod($h, 24);
print "$d days, $h hours, $m minutes, $s seconds.\n";
</code>
<p>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.
<p>I took a look at the inline-c stuff, but that doesn't help for the same reasons.
<p>I also took a quick look at the overloading capabilities but I am not familiar enough with Perl to understand that yet.
<p>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?
<p>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?
<p>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?