Databases Reference
In-Depth Information
return sum(@_)/(@_);
Note that the $Total variable is defined only within the sum( ) function, since it's en-
closed by the function braces.
Save this program as sum_average.floating.pl and then run it by typing:
$ ./sum_average.functions.pl
The total is: 13
The average is: 4.33333333333333
Of course, we can use variables instead of hardcoding values in the program. For ex-
ample, to accept the list of numbers from the command line, we can rewrite the two
print lines as:
print "\nThe total is: ", sum(@ARGV);
print "\nThe average is: ", average(@ARGV);
allowing us to call this program as:
$ ./sum_average.functions.pl 19 313 110
The total is: 442
The average is: 147.33333333333333
The value for the average has more precision than we'd generally need, and the numbers
aren't aligned. We can use the printf function to format the values using a format
specifier before printing them. The format specifiers you are most likely to come across
are:
%d
Integer number (decimal)
%f
Number with a decimal fraction (floating point)
%s
String of characters
For our example, we could write:
printf "\nThe total is: %10d", sum(1, 5, 7);
printf "\nThe average is: %10.2f", average(1, 5, 7);
The value of sum(1, 5, 7) is mapped to the format specifier %10d , which sets aside 10
decimal places for the sum. Similarly, in the second statement, the value of
average(1, 5, 7) is mapped to the format specifier %10.2f , which sets aside 10 char-
acters total for the average and specifies that only 2 decimal places should be displayed.
In other words, we leave room for 7 places to the left of the decimal point, 1 character
for the decimal point itself, and 2 places for the decimal part of the number. With these
statements, the program output would be:
The total is: 13
The average is: 4.33
which looks much nicer.
 
Search WWH ::




Custom Search