5

直到最近(即 C99),模运算符的行为是在 C 中定义的实现。由于 Perl 5 是用 C 编写的,它是否依赖于用于构建它的 C 编译器的行为?

4

2 回答 2

10

不,Perl 5 定义了模运算符 in perlop,甚至还进行了测试以确保它按文档说明工作。

来自 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;

但是,如果您使用integer编译指示,那么您将受到 C 编译器的怜悯。

于 2010-08-31T15:40:37.870 回答
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.

于 2010-08-31T18:39:19.840 回答