Function log() in Perl

In the Perl programming language has a built-in function log().

Function log() returns the natural logarithm of the specified number.

Here's an example:

▶ Run

print log(10);

The program will display 2.30258509299405.


If the function log() not given no arguments, the function works with default variable $_:

▶ Run

$_ = 3;

print log(); # 1.09861228866811

Standard using log() is to pass it a single argument.

If the transfer function log() more than one argument, it will be an error and code execution will be stopped.

Too many arguments for log at line 3, near "2)"
Execution of aborted due to compilation errors.

When you try to calculate the natural logarithm of zero is an error:

▶ Run

Can't take log of 0 at line 3.

Return value

Function log() always returns a number.

The use of other grounds

Function log() returns the natural logarithm, i.e. logarithm base e. If you want to calculate the logarithm to another base, then you can write function:

▶ Run

use strict;
use warnings;
use feature qw(say);

sub log_base {
    my ($base, $n) = @_;

    return log($n)/log($base);

say log_base(2, 4); # 2
say log_base(2, 256); # 8
say log_base(10, 1000); # 3

Official documentation

Here is the output of the command perldoc -f log:

    log EXPR
    log     Returns the natural logarithm (base *e*) of EXPR. If EXPR is
            omitted, returns the log of $_. To get the log of another base,
            use basic algebra: The base-N log of a number is equal to the
            natural log of that number divided by the natural log of N. For

                sub log10 {
                    my $n = shift;
                    return log($n)/log(10);

            See also "exp" for the inverse operation.

Related topics

Other articles