How should I do integer division in Perl?

Bryan Denny picture Bryan Denny · Feb 12, 2009 · Viewed 113.4k times · Source

What is a good way to always do integer division in Perl?

For example, I want:

real / int = int

int / real = int

int / int = int

Answer

Michael Ratanapintha picture Michael Ratanapintha · Feb 12, 2009

The lexically scoped integer pragma forces Perl to use integer arithmetic in its scope:

print 3.0/2.1 . "\n";    # => 1.42857142857143
{
  use integer;
  print 3.0/2.1 . "\n";  # => 1
}
print 3.0/2.1 . "\n";    # => 1.42857142857143