Perl sqrt() function

In the Perl programming language has a built-in function sqrt(). This function returns the square root of its argument.

Here's an example:

▶ Run

print( sqrt(2) );

This program will display the number 1.4142135623731.


my $value = sqrt($number);

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

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

▶ Run

$_ = 4;

print( sqrt() );

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

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

Return value

If the program is not used Perl module Math::Complex, the result of the function sqrt() is always a number.

But if the program has a module Math::Complex, then the result can be a string the last character which is letter 'i', for example '1.73205080756888i'.

In case of negative values of the argument

If the program is not used Perl module Math::Complex and functions sqrt() passed a negative value the exception will be thrown and the program ends:

▶ Run

print( sqrt(-9) );
Can't take sqrt of -9 at line 3.

When using the module Math::Complex function sqrt() works with negative values. Here is a sample program which displays the text 3i.

▶ Run

use Math::Complex;

print( sqrt(-9) );

Official documentation

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

       sqrt EXPR
       sqrt    Return the positive square root of EXPR.  If EXPR is omitted,
               uses $_.  Works only for non-negative operands unless you've
               loaded the "Math::Complex" module.

                   use Math::Complex;
                   print sqrt(-4);    # prints 2i

Other articles