codescracker


perl

Perl Formats



« Previous Tutorial Next Tutorial »


As you know, PERL stands form Practical Extraction and Reporting Language. And PERL is basically used to write formatted reports. Perl uses a writing template, 'format' to output the reports. Therefore, to use format feature, you must have to define format first, and then you are eligible to use that format to write any formatted data.

Define a Format in Perl

Here is the general form to define a format in perl:

format FormatName =
fieldline
value_one, value_two, value_three
fieldline
value_one, value_two
.

Here, the FormatName is the name of the format, the fieldline is the particular way, the data should be formatted, the value lines is the values that will be entered into the fieldline. You end the format with a single period.

The next fieldline can contain any text/fieldholders. The fieldholders hold the space for the data that will be placed there at later time/date. A fieldholder has the format:

@<<<<

The above fieldholder is left-justified, with a field space of 5. You must count the at (@) sign and the < sign to know the number of spaces in the field. Other fieldholders include:

@>>>> right-justified
@|||| centered
@####.## numeric field holder
@* multiline field holder

Following is the example of perl format:

format STUDENT =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<< 
$name $age
@#####.##
$fee
===================================

In the above example, the $name will be written as left justified within 22 characters spaces and after that, the age will be written in two spaces.

Perl Format Example

Here is an example program, helps you in understanding the format in perl:

#!/usr/bin/perl

format STUDENT =
===================================
@<<<<<<<<<<<<<<<<<<<< @<< 
$name $age
@#####.##
$fee
===================================
.

select(STDOUT);
$~ = STUDENT;

@n = ("Deepak", "Rajat", "Vikrant");
@a  = (18, 16, 14);
@s = (2000.00, 2500.00, 4000.000);

$i = 0;
foreach (@n)
{
   $name = $_;
   $age = $a[$i];
   $fee = $s[$i++];
   write;
}

When the above code is executed, it will produce the following output:

===================================
Deepak                   18
  2000.00
===================================
===================================
Rajat                    16
  2500.00
===================================
===================================
Vikrant                  14
  4000.00
===================================

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test