If Perl already links to libm, why aren't any of the functions exposed to the user?

362 Views Asked by At

Perl already links to libm.

$ ldd $(which perl)
    ...
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fd8ce2ea000)
    ...

So if Perl already links to libm, why aren't often used features like ceil, floor, and pow provided as CORE::GLOBALs or provided in another namespace? Why does perldoc -q ceil point to POSIX.pm as a source for this function, and why does Math::Libm even exist?

Python also links to libm which is exposed to the user when you run import math with the symbols available in the module math and can be referenced from outside like math.ceil(num)

1

There are 1 best solutions below

7
On

Perl does have maths functions built in: just its idea of the functions you might need are on par with a 1970s minicomputer. There are all the ones I could find:

#!/usr/bin/env perl
# maths_builtins.pl - some (all?) of the libm functions built in to Perl
# scruss - 2021-05

my $val = -1.234;

print 'abs(', $val, ')', "\t=  ", abs($val), "\n";

my $pi = 4 * atan2( 1, 1 );
print '4*atan2(1,1)', "\t=  ", $pi, "\t(= π)", "\n";
print 'cos(π/6)', "\t=  ", cos( $pi / 6 ), "\n";

my $e = exp(1);
print 'exp(1)', "\t\t=  ", $e, "\t(= e)", "\n";
print 'int(', $val, ')', "\t= ", int($val), "\n";
print 'log(e)', "\t\t=  ", log($e), "\n";
print 'sin(π/6)', "\t=  ", sin( $pi / 6 ), "\n";
print 'sqrt(3)/2', "\t=  ", sqrt(3) / 2, "\n";
print 'sqrt(3)**2', "\t=  ", sqrt(3)**2, "\n";
exit;

resulting in:

abs(-1.234)     =  1.234
4*atan2(1,1)    =  3.14159265358979     (= π)
cos(π/6)        =  0.866025403784439
exp(1)          =  2.71828182845905     (= e)
int(-1.234)     = -1
log(e)          =  1
sin(π/6)        =  0.5
sqrt(3)/2       =  0.866025403784439
sqrt(3)**2      =  3

Note that instead of a pow() function, Perl has the ** operator, just like FORTRAN does. You don't get a tan() function, because that's sin($x)/cos($x). If you need other transcendental functions, that's why they put the trigonometric functions table (PDF, p.39) in all good programming books.

I can't recall ever using or needing ceil() or floor() myself, but Perl missing sgn() as a builtin gets me every time. Since Perl is a typeless scripting language at heart, numeric gardening tasks like rounding can already be done with string functions such as sprintf "%.f", $val.