|
#!/usr/bin/perl -w
|
|
# A better way to work with financial values
|
|
use strict;
|
|
sub money ($) {
|
|
# Given a non-negative integer number of pennies,
|
|
# returns that figure as a dollars-and-cents amount,
|
|
# with dollar sign, something like '$12345.67'.
|
|
my $num = shift;
|
|
warn "Bad amount of money: $num" if $num < 0;
|
|
|
|
$num = sprintf "%03d", $num; # make it a string
|
|
substr($num, -2, 0) = "."; # add the decimal point
|
|
'$' . $num; # return value
|
|
}
|
|
my $total = 1908 + 201; # integers now
|
|
my $expected_total = 2109;
|
|
|
|
print "The total is ", money($total), "\n";
|
|
print "The expected total was ", money($expected_total), "\n";
|
|
if ($total == $expected_total) { # Comparing numbers of pennies
|
|
print "They are equal.\n";
|
|
} else {
|
|
print "They aren't equal.\n";
|
|
}
|