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.
Floating-Point Numbers$no = 42; $no = -10; $no = 0;
Scientific Notation$no = 3.14; # decimal point! $no = -123.456; $no = 0.5;# or .5 $no = 9.0;# or 9.
$no = 6.022e23; # Avogadro's number $no = 1.602e-19;# elementary charge of an electron
What's happening here?$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);
Notice the following: the scalar$bird = "penguin"; $no_of_birds = 2; print("I saw " . $no_of_birds . " " . $bird . "s."); # I saw 2 penguins.
$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");
You can also print numbers along with text or other variables:$num1 = 42; $num2 = 3.14; print($num1); # 42 print("\n");# prints a newline print($num2);# 3.14 print("\n");# prints a newline
You can format the output of numbers using$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"
This will print the number with two digits after the decimal point. Adjust the format string$num3 = 1234.56789; printf("Formatted number: %.2f\n", $num3); # Prints "Formatted number: 1234.57"
printf("Formatted number: %.2f\n", 10/3); # Prints "Formatted number: 3.33"
To truncate a number use$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 be sure operations are done on only integers, include the module$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
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
This will print numbers from 1 to 10, each on a new line.for ($i = 1; $i < 11; $i++) { print "$i\n"; }
Usingforeach $i (1..10) { print "$i\n"; }
This will also print numbers from 1 to 10.$i = 1; while ($i <= 10) { print "$i\n"; $i = $i + 1; # shorter: $i++ }
This will also print numbers from 1 to 10.$i = 1; until ($i > 10) { print "$i\n"; $i++; }
int() and sprintf(): Converts a number to an integer.$absolute_value = abs(-10); # $absolute_value will be 10
sqrt(): Returns the square root of a number.$integer_value = int(3.14); # $integer_value will be 3 $formatted_value = sprintf("%.2f", 3.14159);# $formatted_value will be 3.14
rand(): Generates a random number between 0 and 1.$square_root = sqrt(16); # $square_root will be 4
rand(): Generates a random integer number between 0 and 100.$random_number = rand(); # Generates a random number between 0 and 1 (1 exclusive)
To generate 10 random integers within the inclusive range [1, 10], do:$random_number = int(rand(100)); # Generates a random integer between 0 and 100 (100 exclusive)
cos(), sin(), tan(): Trigonometric functions.$min = 1; $max = 10; for ($i = 0;$i < 10;$i++) { $random_number = int(rand($max - $min + 1)) + $min; print($random_number . "\n"); }
log(), log10(), exp(): Exponential and logarithmic 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
min() and max(): Returns the minimum or maximum value among the provided numbers.$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
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.$minimum_value = min(5, 10, 3); # $minimum_value will be 3 $maximum_value = max(5, 10, 3);# $maximum_value will be 10
$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 );
Here's an example to illustrate their usage:$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.
$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
Perl has support for handling big numbers through various modules, notably$large_number = 1_234_567_890; print $large_number; # Output: 1234567890
1. How to swap 0 to 1 and vice versa?
The long way:
A shorter way:if ($change_all == 0) { $change_all = 1; } elsif ($change_all == 1) { $change_all = 0; }
The shortest way:($change_all) ? ($change_all = 0) : ($change_all = 1);
$change_all = 1 - $change_all;
Output: 0.12 (thanks to https://stackoverflow.com/users/2600099/matija-nalis)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));
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
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