1b. Scalar: number

As already said, a number is also an example of a single value or a scalar. Perl, like many programming languages, supports various data types for handling numbers. These include integers, floating-point numbers, and scientific notation.

You can perform arithmetic operations on numbers using operators like +, -, *, /, % (modulo), ** (exponentiation), and comparison operators like ==, !=, <, <=, >, >= etc.

1.1 Create

Integers
Integers are whole numbers without a decimal point. For example:
$no = 42;
$no = -10;
$no = 0;
Floating-Point Numbers
Floating-Point Numbers are numbers with a decimal point. For example:
$no = 3.14; # decimal point!
$no = -123.456;
$no = 0.5; # or .5
$no = 9.0; # or 9.
Scientific Notation
Representing numbers using scientific notation, often used for very large or very small numbers. For example:
$no = 6.022e23; # Avogadro's number
$no = 1.602e-19; # elementary charge of an electron

1.2 Access

It's important to note that while Perl allows you to treat numbers as strings and vice versa
$decimal_number = "3.14";
$length = length($decimal_number); # 4 

$no_1 = "5";
$no_2 = "6";
$sum = $no_1 + $no_2;
print("$sum\n"); # 11

$no = "3.14";
$base = substr($no, 0, 1);
What's happening here?
$bird = "penguin";
$no_of_birds = 2;
print("I saw " . $no_of_birds . " " .  $bird . "s."); # I saw 2 penguins.
Notice the following: the scalar $no_of_birds was defined as a number: $no_of_birds = 2. However, despite of this, the output is: 'I saw 2 penguins'. In other words, the dot operator evaluates the number 2 in string context!

However, it's generally good practice to maintain a clear distinction between the two data types for better code clarity and readability.
$num1 = 42;
$num2 = 3.14;

$sum = $num1 + $num2;
$difference = $num1 - $num2;
$product = $num1 * $num2;
$quotient = $num1 / $num2;

print("Sum: ". $sum . "\nDifference: " . $difference . "\nProduct: " . $product . "\nQuotient: " . $quotient ."\n");

1.3 Print

You can print numbers using the print function. Here's how you can do that:
$num1 = 42;
$num2 = 3.14;

print($num1); # 42
print("\n"); # prints a newline
print($num2); # 3.14
print("\n"); # prints a newline
You can also print numbers along with text or other variables:
$age = 30;

print("The answer to life, the universe, and everything is: $num1\n"); # prints "The answer to life, the universe, and everything is: 42
print("Pi is approximately equal to: $num2\n"); # prints "Pi is approximately equal to: 3.14"
print("I am $age years old\n"); # prints "I am 30 years old"
You can format the output of numbers using printf function for more control over how the numbers are printed:
$num3 = 1234.56789;
printf("Formatted number: %.2f\n", $num3); # Prints "Formatted number: 1234.57"
This will print the number with two digits after the decimal point. Adjust the format string ("%.2f") as needed to suit your formatting requirements.
printf("Formatted number: %.2f\n", 10/3); # Prints "Formatted number: 3.33"
1.3.1 Rounding
In the next code +0.5 is the magical sauce to do rounding instead of truncating.
$no = 0.1153846153846;
$factor = 10**2; # 2 digits after decimal point
$no_def =  int( $no * $factor + 0.5 ) / $factor;
print($no_def . "\n"); # 0.12

$no = 0.1153846153846;
$factor = 10**4; # 4 digits after decimal point
$no_def =  int( $no * $factor + 0.5 ) / $factor;
print($no_def . "\n"); # 0.1154
To truncate a number use int (ignoring the fractional part) or substr (using the number as a string):
$no = 7.1153846153846;
$no_digits_after = 3;
$no_trunc = substr( $no, 0, (index($no,) + 1 + $no_digits_after) );
print($no_trunc . "\n"); # 7.115

$no = 7.1153846153846;
$no_trunc = int( $no );
print($no_trunc . "\n"); # 7
To be sure operations are done on only integers, include the module integer:
use integer;
$x = 5.8;
print($x . "\n"); # 5.8 ... no operation on $x was done
print(-$x . "\n"); # -5
$y = 2.5;
print($x + $y . "\n"); # 7

1.4 Iterate

You can iterate over numbers using loops such as for, foreach, while, or until (see chapter 7: Looping). Here are examples of each:

Using for loop:
for ($i = 1; $i < 11; $i++) {
    print "$i\n";
}
This will print numbers from 1 to 10, each on a new line.

Using foreach loop (which is essentially the same as for in Perl):
foreach $i (1..10) {
    print "$i\n";
}
Using while loop:
$i = 1;
while ($i <= 10) {
    print "$i\n";
    $i = $i + 1; # shorter: $i++
}
This will also print numbers from 1 to 10.

Using until loop:
$i = 1;
until ($i > 10) {
    print "$i\n";
    $i++;
}
This will also print numbers from 1 to 10.

Choose the appropriate loop based on your specific requirements and preferences. All of these loops are capable of iterating over numbers, but they may have different use cases depending on the context of your program.

1.5 Operate

You can use various built-in functions to manipulate numbers. Here are some commonly used functions:

abs(): Returns the absolute value of a number.
$absolute_value = abs(-10); # $absolute_value will be 10
int() and sprintf(): Converts a number to an integer.
$integer_value = int(3.14);  # $integer_value will be 3
$formatted_value = sprintf("%.2f", 3.14159);   # $formatted_value will be 3.14
sqrt(): Returns the square root of a number.
$square_root = sqrt(16); # $square_root will be 4
rand(): Generates a random number between 0 and 1.
$random_number = rand(); # Generates a random number between 0 and 1 (1 exclusive)
rand(): Generates a random integer number between 0 and 100.
$random_number = int(rand(100)); # Generates a random integer between 0 and 100 (100 exclusive)
To generate 10 random integers within the inclusive range [1, 10], do:
$min = 1;
$max = 10;

for ($i = 0;$i < 10;$i++) {
  $random_number = int(rand($max - $min + 1)) + $min;
  print($random_number . "\n");
}  
cos(), sin(), tan(): Trigonometric functions.
$cos_value = cos(0); # $cos_value will be 1
$sin_value = sin(0); # $sin_value will be 0
$tan_value = tan(45); # $tan_value will be approximately 1
log(), log10(), exp(): Exponential and logarithmic functions.
$log_value = log(10); # Natural logarithm of 10
$log10_value = log10(100); # Base 10 logarithm of 100
$exp_value = exp(1); # Exponential function e^1
min() and max(): Returns the minimum or maximum value among the provided numbers.
$minimum_value = min(5, 10, 3); # $minimum_value will be 3
$maximum_value = max(5, 10, 3); # $maximum_value will be 10
These are just a few examples of functions available in Perl for working with numbers. Perl offers a rich set of mathematical functions and operators for handling numeric data.

1.5.1 Short assignment operators

$x += 2; # $x = $x + 2;
$x -= 2; # $x = $x - 2;
$x /= 2; # $x = $x / 2;
$x *= 2; # $x = $x * 2;
$x **= 2; # $x = $x ** 2;
$x %= 2; # $x = $x % 2;
$x += ( ($a ** 5) / 2 ); # $x = $x + ( ($a ** 5) / 2 );

1.5.2 Increment and decrement operators

The ++ and -- operators are used to increment and decrement the value of variables, respectively. They can be used both as prefix and postfix operators.
$no = 20;
++$no; # Prefix Increment: increases the value of the variable by 1 and returns the new value, here 21.

$no = 20;
--$no; # Prefix Decrement: decreases the value of the variable by 1 and returns the new value, here 19.

$no = 20;
$no++; # Postfix Increment: returns the current value of the variable and then increases it by 1.

$no = 20;
$no--; # Postfix Decrement: returns the current value of the variable and then decreases it by 1.
Here's an example to illustrate their usage:
$x = 5;
$y = 10;

$result_1 = ++$x; # $x is incremented before its value is assigned to $result_1: $x is now 6, $result_1 is 6
$result_2 = $y--; # $y is decremented after its value is assigned to $result_2: $result_2 is 10, $y after assigning 9

print("Result of prefix increment: $result_1\n"); # Output: Result of prefix increment: 6
print("Result of postfix decrement: $result_2\n"); # Output: Result of postfix decrement: 10

1.5.2 Bit operations

You can perform bit manipulation operations using bitwise operators. These operators allow you to manipulate individual bits within integers. I do not use them now. So do a Google search on 'perl bit operations'.

1.5.3 Hexadecimal and octal numbers

Again: I do not use them till now. So I've the same advice as previously: do a Google search on 'perl hexadecimal and octal numbers'.

1.6 Big numbers

In Perl, you can use underscores _ to improve the readability of large numbers in your code. These underscores are ignored by Perl and serve only as visual separators.
$large_number = 1_234_567_890;
print $large_number; # Output: 1234567890
Perl has support for handling big numbers through various modules, notably Math::BigInt. This module allows you to work with integers of arbitrary size, which is particularly useful when dealing with numbers larger than what can be represented by standard numeric types. Additionally, Perl's native floating-point arithmetic has limited precision, so if you need to work with very large floating-point numbers with high precision, using external modules like Math::BigFloat might be more appropriate.

1.7 Number: how-to


1. How to swap 0 to 1 and vice versa?

The long way:

if ($change_all == 0) {
  $change_all = 1;
} 
elsif ($change_all == 1) {
  $change_all = 0;
}
A shorter way:
($change_all) ? ($change_all = 0) : ($change_all = 1);
The shortest way:

$change_all = 1 - $change_all;

2. How to format a number (without (s)printf)?
sub round
{
  my ($value, $places) = @_;
  my $factor = 10**$places;
  return int($value * $factor + 0.5) / $factor; # +0.5 is magical sauce to do rounding instead of truncating
}
$no = 0.1153846153846;
print(round($no,2));
Output: 0.12 (thanks to https://stackoverflow.com/users/2600099/matija-nalis)


3. How to split a number into its individual digits?
The solutions is to 'cast' a numbers as a string. An example is to determine if a number is a Niven or Harshad number, i.e. a positive integer that is divisible by the sum of its digits. The number 21 is e.g. a Niven number, because 21 can be divided by (2 +1). Below a Niven number checker:

sub is_niven_number {
    $number = shift;
    @digits = split( //, $number );
    $sum    = 0;

    foreach $digit (@digits) {
        $sum += $digit;
    }

    return ( $number % $sum == 0 );
}

$num = 18; # Replace with the number you want to check
if ( is_niven_number($num) ) {
    print("$num is a Niven number.\n");
}
else {
    print("$num is not a Niven number.\n");
}


4. How to pick a random integer in [a,b] and a < b?

($min, $max) = (5, 25);
$number = $min + int(rand($max - $min));
print("$number\n"); # Output e.g. 23


5. How to convert an real number to a string with two decimal places?

$number = sprintf("%.2f", 3.14567890);
print("This string contains the $number\n"); # Output: This string contains the number 3.15

6. How to check if a number is an integer or a floating point number?
use autobox::universal qw(type); # invoke module

$floating_point = 1.00;
$integer = 1;

print(type($integer),"\n"); # Output: INTEGER
print(type($floating_point), "\n"); # Output: FLOAT

$floating_point = $floating_point * $integer;
print(type($floating_point), "\n"); # Output: INTEGER

$floating_point = 1.00;
$floating_point = $floating_point ** 2;
print(type($floating_point), "\n"); # Output: FLOAT