Perl: understanding modulo operation on negative numbers (e.g. -10%3)

Viewed 3243

I'm learning Perl (5.14) and I'm a bit stuck on modulo with negative numbers. As an example, let's take a look at variations on 10%3.

To begin,

perl -le 'print -10%-3'

yields -1, as expected.

But,

perl -le 'print -10%3'

yields 2.

And,

perl -le 'print 10%-3'

yields -2.

I do not understand the last two results. I would expect only 1 or -1 as a result for any variation on 10%3. Why should 2, either positive or negative, be returned as a result?

2 Answers
Related