View Category

Find the distance between two points

perl
use Math::Complex;
$a = Math::Complex->make(0, 3);
$b = Math::Complex->make(4, 0);
$distance = abs($a - $b);
my @a=(0, 3);
my @b=(4, 0);
my $distance = sqrt( ($a[0]-$b[0])**2 + ($a[1]-$b[1])**2 );

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
perl
sprintf("%08d", 42);

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
perl
sprintf("%-6d", 1024);

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
perl
sprintf("%.2f", 7/8);

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
perl
sprintf("%10d", 73);

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
perl
my $range = 100;
my $minimum = 100;

my $random_number = int(rand($range)) + $minimum;

print "$random_number\n";

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
perl
srand(12345);
@list1 = map(int(rand(100)+1), (1..5));

srand(12345);
@list2 = map(int(rand(100)+1), (1..5));

print join(', ', @list1) . "\n";
print join(', ', @list2) . "\n";