Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the behavior of % with negative operands defined in Perl 5?

Tags:

modulo

perl

Until recently (i.e. C99), the behavior of the modulo operator was implementation defined in C. Since Perl 5 is written in C, is it reliant on the behavior of the C compiler used to build it?

like image 363
Chas. Owens Avatar asked Aug 31 '10 15:08

Chas. Owens


2 Answers

No, Perl 5 defines the modulo operator in perlop and even has tests to ensure it works as documented.

from perl/t/op/arith.t

tryeq $T++,  13 %  4, 1;
tryeq $T++, -13 %  4, 3;
tryeq $T++,  13 % -4, -3;
tryeq $T++, -13 % -4, -1;

However, if you use the integer pragma, you are at the mercies of the C compiler.

like image 189
Chas. Owens Avatar answered Oct 23 '22 23:10

Chas. Owens


Perl implements its own modulo operator, but you can get to the one from your C compiler by using the integer pragma. perlop says

Note that when use integer is in scope, "%" gives you direct access to the modulo operator as implemented by your C compiler. This operator is not as well defined for negative operands, but it will execute faster.

That is, you have to be careful when you are using integer because the modulo might give you different answers.

like image 26
brian d foy Avatar answered Oct 23 '22 22:10

brian d foy