Perl Programming - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Perl Format

Perl Format

shape Introduction

This chapter demonstrates Perl Format which is used to generate the exacted reports similar to the output screen or in a file and following are the concepts covered in this chapter.
  • Perl Formats

Perl Formats

shape Description

Perl has a mechanism using which user can generate reports. using this feature user can make reports exactly the way we want while printing on the Output screen or in a file. a simple format can be written using printf or sprint functions available in Perl is as shown in below snippet. [code] printf "%05d\n", 30; [/code] Which includes leading zeros in front of number 30 making a total count of digits to 5 which can be used for sprintf as shown below. [code] sprintf "%05d\n", 30; # This will print the same as printf. [/code] The table below demonstrates the particular method write to print the data on output screen or into the file.
Symbol Description
@ Which is used to represent the start of the field holder.
< Which is the left alignment of the text.
> Which is the right alignment of the text.
| center alignment.
# Nueric if multiple # provided.
. Decimal Point.
^ Start of field holder.
~ Line should be empty if variable is empty.
@* Multiple lines.
The code below demonstrates the Perl Formats as shown below. [perl] format EMPLOYEE = =================================== @<<<<<<<<<<<<<<<<<<<<<< @<< $name $age @#####.## $salary =================================== . select(STDOUT); $~ = EMPLOYEE; @n = ("wilson", "Tony", "kate"); @a = (20,30, 40); @s = (2000.00, 2500.00, 4000.000); $i = 0; foreach (@n){ $name = $_; $age = $a[$i]; $salary = $s[$i++]; write; } [/perl] Result By running the above code in a Perl command line user can get the following output as shown in below image. Header Report If user interested in adding a header to the report. which header will be printed on top of each page. Which is a very easy process. apart from defining a template, you would have to define a header and assign it to $^ or $FORMAT_TOP_NAME variable. The code below demonstrates the Header report as shown below. [perl] format EMPLOYEE = =================================== @<<<<<<<<<<<<<<<<<<<<<< @<< $name $age @#####.## $salary =================================== . format EMPLOYEE_TOP = =================================== Name Age =================================== . select(STDOUT); $~ = EMPLOYEE; $^ = EMPLOYEE_TOP; @n = ("wilson", "Tony", "kate"); @a = (20,30, 40); @s = (2000.00, 2500.00, 4000.000); $i = 0; foreach (@n){ $name = $_; $age = $a[$i]; $salary = $s[$i++]; write; } [/perl] Result By running the above code in a Perl command line user can get the following output as shown in below image.

Sumary

shape Key Points

  • User can also headers to the page.
  • fieldline contain any text or file folders.
  • FormatName represent the name of the format.