How to get the number PI in Perl

Task. Need to code a Perl program to get the number PI.

The decision

The easiest way to get PI into a Perl program is to use the library Math::Trig. Library Math::Trig comes with Perl, so if you have Perl, this library is available to additionally install nothing.

Here is an example Perl program that displays PI on the screen:

▶ Run
#!/usr/bin/perl

use Math::Trig;

print pi();

The program will display 3.14159265358979.

  • use Math::Trig; — we connect library Math::Trig. As soon as we connected this library, we immediately became available a few functions that are defined in this library.
  • print pi(); — called function pi, which became available due to the connection library. And display the result returned by this function.

If you do not connect the library use Math::Trig; in the program, then the program error:

Undefined subroutine &main::pi called at script.pl line 3.

The use of the symbol π in variable name

The number PI is often denoted by the Greek letter π.

The Perl programming language lets you create variables not only Latin characters but also of the many Unicode characters. Therefore, it is possible to create a variable with the interesting name . Here is a sample program:

▶ Run
#!/usr/bin/perl

use utf8;
use Math::Trig;

my $π = pi();

print $π;

Enter this program exactly the same as the last one. Will appear on the screen 3.14159265358979.

  • use utf8; — say your code is encoded utf8
  • use Math::Trig; — as in the previous embodiment, a plug-in library.
  • my $π = pi(); — create a variable and put back the function result pi
  • print $π; — print the contents of a variable on the screen

This is an interesting use of language features, but not particularly comfortable. Not all people can to gain symbol π on the keyboard. It often happens that if in the text you want to insert the symbol π, then this symbol just copy from somewhere (e.g., from the Wikipedia page about the number PI).

If you still need a variable with the number PI, it is more practical though less interesting to use a variable with the name $pi.

Other articles

Comments