Previous | Table of Contents | Next |
Exercise: A Formatted ReportA task that comes up inevitably when you're dealing with computers is formatting raw data into a report. Computer programs exchange data in formats that are difficult for humans to read, and a common task is taking that data and formatting it into a human-friendly report. For this exercise, you're given a set of employee records that contain information about some mythical employees, including hourly wages, number of hours worked, names, and employee numbers. The exercise takes that data and reformats it into a nice report. You can easily modify this same kind of program to print other kinds of reports. The data for the exercise is contained within an array initialized at the beginning of the program. In a real report, the data would probably come from a file on disk. Modifying this exercise to use an external file is left as an exercise for later. Using your text editor, type the program from Listing 9.1 and save it as Employee. Do not type the line numbers. Make the program executable according to the instructions you learned in Hour 1, "Getting Started with Perl." When you're all done, try running the program by typing the following at a command line:
Employee
or, if you cannot make the program executable,
perl Employee
Listing 9.1. Complete Listing of Employee Program1: #!/usr/bin/perl -w 2: 3: use strict; 4: 5: my @employees = ( 6: 'Smith,Bob,123101,9.35,40', 7: 'Franklin,Alice,132912,10.15,35', 8: 'Wojohowicz,Ted,198131,6.50,39', 9: 'Ng,Wendy,141512,9.50,40', 10: 'Cliburn,Stan,131211,11.25,40', 11: ); 12: 13: sub print_emp { 14: my($last,$first,$emp,$hourly,$time)= 15: split(',', $_[0]); 16: my $fullname; 17: $fullname = sprintf("%s %s", $first, $last); 18: printf("%6d %-20s %6.2f %3d %7.2f\n", 19: $emp, $fullname, $hourly, $time, 20: ($hourly * $time) + .005 ); 21: } 22: 23: @employees = sort { 24: my ($L1, $F1)=split(',', $a); 25: my ($L2, $F2)=split(',', $b); 26: return( $L1 cmp $L2 # Compare last names 27: || # If they're the same... 28: $F1 cmp $F2 # Compare first 29: ); 30: } @employees; 31: 32: foreach (@employees) { 33: print_emp($_); 34: }
Listing 9.2 shows a sample of the Employee program's output. Listing 9.2. Output from the Employee Program131211 Stan Cliburn 11.25 40 450.00 132912 Alice Franklin 10.15 35 355.25 141512 Wendy Ng 9.50 40 380.00 123101 Bob Smith 9.35 40 374.00 198131 Ted Wojohowicz 6.50 39 253.50 |
Previous | Table of Contents | Next |