Scripsit ille »John Andrews« john_b_andrews@yahoo.com:
Thanks to Rudolf and Mark for answering my question.
I don’t know what version of Perl you are both using, but
my Perl (5.6.1) on Linux does truncate to zero, agreeing
with C.
Here is the Perl program:
use integer;
^^^^^^^^^^^^
That is, use the integer type of the platform you are using. Its behaviour
is implementation-defined.
$a = -3;
$b = 100;
$c = $a / $b;
$d = $a % $b;
print $c, “\n”;
print $d, “\n”;
Here is the output:
0
-3
The same program in Ruby gives:
-1
97
That’s because Ruby doesn’t have “implementation-dependent integers”. You
notice you haven’t used that “use integer” in your Ruby code.
And now check what Perl does if you DON’T use that ‘use integer’ and use
floating-point arithmetic:
$a = -3;
$b = 100;
$d = $a % $b;
$c = $a / $b; # there’s no integer division operator in Perl…
$c = ($a - $d) / $b; # this is defined to be always an integer
print $c, “\n”;
print $d, “\n”;
and that outputs
-1
97
You can do integer division in Perl only using this identity:
$quotient = ($a - ($a % $b)) / $b;
Anything else would be inconsistent with the % operator.
BTW, you would know if you have read perldoc integer:
···
,–
Internally, native integer arithmetic (as provided by your C compiler)
is used. This means that Perl’s own semantics for arithmetic opera-
tions may not be preserved. One common source of trouble is the modu-
lus of negative numbers, which Perl does one way, but your hardware may
do another.
% perl -le 'print (4 % -3)'
-2
% perl -Minteger -le 'print (4 % -3)'
1
`–
perldoc perlop says something similar about the % operator.
But in some sense you may be right - perhaps a built-in type for platform
dependent integers would be useful. But since one would do that to gain
SPEED, it cannot be an external class… but if it’s something internal,
one would probably get a type which doesn’t behave well in the object
model. No, I wouldn’t like it.
In Ruby you have only one type of % and / semantics - the one you are
surprised of. In Perl, it’s the same unless you use integer.
–
“Aus Ehrfurcht, hoff ich, soll es mir gelingen,
Mein leichtes Naturell zu zwingen;
Nur zickzack geht gewöhnlich unser Lauf.”
“Ei! ei! Er denkts den Menschen nachzuahmen.”