Article
The Perl Tutorial: What's Perl?
Report Writing
As we discussed at the beginning of the tutorial, Perl stands for Practical Extraction and Reporting Language, and we'll now discuss using Perl to write reports.
Perl uses a writing template called a 'format' to output reports. To use the format feature of Perl, you must:
- Define a Format
- Pass the data that will be displayed on the format
- Invoke the Format
Define the format as follows:
format FormatName =
fieldline
value_one, value_two, value_three
fieldline
value_one, value_two
.
FormatName represents the name of the format. The fieldline is the specific way the data should be formatted. The values lines represent the values that will be entered into the field line. You end the format with a single period.
fieldline can contain any text or fieldholders. Fieldholders hold space for data that will be placed there at a later date. A fieldholder has the format:
@<<<<
This fieldholder is left-justified, with a field space of 5. You must count the @ sign and the < signs to know the number of spaces in the field. Other field holders include:
@>>>>right-justified
@||||centered
@####.##numeric field holder
@*multiline field holder
An example format would be:
format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
===================================
.
Only scalar variables can be used - not arrays or hashes. In order to invoke this format declaration we would use the write keyword:
write EMPLOYEE; #send to the output
The problem is that the format name is usually the name of an open file handle, and the write statement will send the output to this file handle. As we want the data sent to the STDOUT, we must associate EMPLOYEE with the STDOUT filehandle. First, however, we must make sure that that STDOUT is our selected file handle, using the select() function:
select(STDOUT);
We would then associate EMPLOYEE with STDOUT by setting the new format name with STDOUT, using the special variable $~:
$~ = "EMPLOYEE";
When we now do a write(), the data would be sent to STDOUT. Remember: if you didn't have STDOUT set as your default file handle, you could revert back to the original file handle by assigning the return value of select to a scalar value, and using select along with this scalar variable after the special variable is assigned the format name, to be associated with STDOUT.