Function abs() in Perl

In the Perl programming language has a built-in function abs(). This function returns the modulus of its argument.

Here's an example:

▶ Run
#!/usr/bin/perl

print abs( -3.14159265358979 );

This program displays 3.14159265358979.

Arguments

my $abs_value = abs($value);

If the functions abs() to pass a single argument, the function will operate on it.

If you do not pass any argument, the function will work with the default variable $_. Here is an example (the program displays the number 8):

▶ Run
#!/usr/bin/perl

$_ = -8;

print abs();

If the functions abs() pass more than one argument, it will error:

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

If the function of the passed string, it is converted to a number. Read more about how Perl converts strings to numbers.

Here is an example of code in which the function abs() works with strings:

▶ Run
#!/usr/bin/perl

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

say abs('Hello');
say abs('-100asdf');
say abs(' -123JK');

This program will display:

0
100
123
Argument "Hello" isn't numeric in abs at script.pl line 7.
Argument "-100asdf" isn't numeric in abs at script.pl line 8.
Argument " -123JK" isn't numeric in abs at script.pl line 9.

If the argument to use undef, the function will return the number 0, but if the code has use warnings;, you will see a warning Use of uninitialized value in abs at script.pl line 6..

Return value

Function abs() always returns a non-negative number.

Official documentation

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

    abs VALUE
    abs     Returns the absolute value of its argument. If VALUE is omitted,
            uses $_.

Related topics

Other articles