# How to use Formats in Perl?

PERLServer Side ProgrammingProgramming Scripts

In order to invoke a format declaration in Perl Script, we would use the write keyword −

write EMPLOYEE;

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 $~ or$FORMAT_NAME as follows −

$~ = "EMPLOYEE"; When we now do a write(), the data would be sent to STDOUT. Remember: if you are going to write your report in any other file handle instead of STDOUT then you can use select() function to select that file handle and rest of the logic will remain the same. ## Example Let's take the following example. Here we have hard coded values just for showing the usage. In actual usage you will read values from a file or database to generate actual reports and you may need to write final report again into a file. Live Demo #!/usr/bin/perl format EMPLOYEE = =================================== @<<<<<<<<<<<<<<<<<<<<<< @<<$name $age @#####.##$salary
===================================
.

select(STDOUT);
$~ = EMPLOYEE; @n = ("Ali", "Raza", "Jaffer"); @a = (20,30, 40); @s = (2000.00, 2500.00, 4000.000);$i = 0;
foreach (@n) {
$name =$_;
$age =$a[$i];$salary = $s[$i++];
write;
}

## Output

When executed, this will produce the following result −

===================================
Ali                20
2000.00
===================================
===================================
Raza              30
2500.00
===================================
===================================
Jaffer            40
4000.00
===================================
Published on 29-Nov-2019 14:34:54