MLUG: Re: [UUG/MLUG] perl and y2k
Re: [UUG/MLUG] perl and y2k
Email address obfuscation in effect -- please click here to turn it off.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
>From the perl documentation (all quoted sections):

  "Binary ``%'' computes the modulus of two numbers. Given integer
   operands $a and $b:"

In Jon King's example, $a=-98 and $b=100.

  "If $b is positive,"

$b=100 and is positive

  "then $a % $b is $a minus the largest multiple of $b that is not greater
   than $a."

The greatest multiple of 100 that is not greater than -98 is 100*-1 = -100.
We subtract -100 from -98 and we get -98-(-100)=2.

So I conclude that Tymm made a mistake, Perl is not broken, and Jon and
Stephen were correct.

Mike



On Wed, 5 Jan 2000, Tymm Twillman wrote:

> you know, this then caused me to go look at perlop(1); description there:
> 
> Binary ``%'' computes the modulus of two numbers. Given integer operands
> $a and $b: If $b is positive, then $a % $b is $a minus the largest
> multiple of $b that is not greater
> than $a. If $b is negative, then $a % $b is $a minus the smallest multiple
> of $b that is not less than $a (i.e. the result will be less than or equal
> to zero). 
> 
> (got that?)
> 
> which means that perl is broken as re: documentation.  Probably so many
> people expect modulus to always return a positive # that they broke it.
> 
> -Tymm
> 
> 
> On Wed, 5 Jan 2000, Jonathan King wrote:
> 
> > 
> > On Wed, 5 Jan 2000, Stephen Montgomery-Smith wrote:
> > 
> > > Jonathan King wrote:
> > >
> > 
> > [snip]
> > 
> > > > Along these lines, and while we all run off to fix our code, some of you
> > > > might be interested in the fact that perl does something potentially
> > > > unexpected with the % operator when the first argument is negative, so
> > > > that:
> > > > 
> > > >     [EMAIL:PROTECTED]$ perl -e '$a=-98; printf("%02d\n",$a%100);'
> > > >     02
> > > > 
> > > 
> > > Hmmm, in my opinion (as a mathematician) that is the correct answer.
> > > I would have expected -98 (in my opinion the wrong answer, but
> > > what I think C does).
> > 
> > Curiousity caused the cat:
> > 
> >     [EMAIL:PROTECTED king]$ cat > triv.c
> >     int main () {
> >     printf("%d\n", -98%100);
> >     }
> >     [EMAIL:PROTECTED king]$ cc -o triv triv.c
> >     [EMAIL:PROTECTED king]$ triv
> >     bash: triv: command not found
> > 
> > Hmm...I wonder why this happened. :-)
> > 
> >     [EMAIL:PROTECTED king]$ ./triv
> >     -98
> > 
> > And, indeed, it is the fact that both C and awk diverges from mathematical
> > convention that causes people to blame perl for a "wrong" answer in this
> > case.
> > 
> > jking