Please send questions to
st10@humboldt.edu .
#!/usr/bin/perl -w
#######################################################
# lect08_sprintf
#
# quickie example of sprintf
#
# modified by Sharon Tuttle from "Learning Perl",
# by Schartz and Phoenix
#
# last modified: 10-11-04
#######################################################
#------------------------------------------------
# print a large monetary number with 2 fractional
# places, and commas if >=1000
#------------------------------------------------
sub big_money
{
# expecting only 1 parameter, ignoring the rest.
# (and immediately, firstly, formatted to
# 1 fractional places)
my $number = sprintf "%.2f", shift @_;
# do-nothing loop: loop through, adding as many
# commas as needed;
# from BEGINNING of number,
# match 0 or 1 negative signs, then 1 or more digits
# (memory #1)
# and then exactly 3 digits (memory #2) ---
# if you CAN,
# then substitute memory #1, comma, memory #2
while ($number =~ s/^(-?\d+)(\d\d\d)/$1,$2/)
{
1; # traditional Perl placeholder...!
}
# put the dollar sign in the right place
$number =~ s/^(-?)/$1\$/;
return $number;
}
# "little" number example
my $pretty_amt_owed = sprintf "\$%.2f", 2.49997;
print "$pretty_amt_owed\n";
# "big" number example
print &big_money(999.8555) . "\n";
print &big_money(1000) . "\n";
print &big_money(-1000.333) . "\n";
print &big_money(5764333.3) . "\n";
# oh, print 'em even prettier!
print "\nPRETTIER...\n";
print "----------------\n";
my @money_list = (999.8555, 1000, -1000.333, 5764333.3);
my $amount;
foreach (@money_list)
{
$amount = $_;
printf "%16s\n", &big_money($amount);
}
print "\n";
# end of lect08_sprintf