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

拟墨画扇 提交于 2020-01-13 10:49:26

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3610687/is-the-behavior-of-with-negative-operands-defined-in-perl-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!