perl formats

‮/:sptth‬/www.theitroad.com

Perl formats are a way to control the layout and formatting of text output in Perl scripts. Formats are defined using the format keyword, and they consist of a series of lines that specify the output format for each field of data.

Here is an example of a simple format that prints a list of names and ages:

format STDOUT =
Name: @<<<<<<<<<<<< Age: @>>
$name, $age
.

my $name = "John";
my $age = 30;
write;

In this example, we define a format using the format keyword and assign it to the standard output (STDOUT). The format consists of two lines: the first line specifies the output format for the name field (@<<<<<<<<<<<<), which means "left-justified in a field of 12 characters"; the second line specifies the output format for the age field (@>>), which means "right-justified in a field of 2 characters". The . character at the end of the format definition marks the end of the format.

We then define two variables $name and $age, and use the write function to output the formatted data. The write function takes the values of the variables and formats them according to the specified format, producing output like this:

Name: John        Age: 30

You can define multiple formats in a Perl script, and switch between them using the select function. For example:

format STDOUT_TOP =
Name             Age
----             ---
.

format STDOUT =
@<<<<<<<<<<<<   @>>
$name, $age
.

select STDOUT_TOP;
write;

$name = "Jane";
$age = 25;
write;

In this example, we define two formats: STDOUT_TOP and STDOUT. We use the select function to switch the output to the STDOUT_TOP format, which prints a header row for the data. We then use the write function to output the header row.

We then assign new values to the $name and $age variables, and use the write function again to output the data using the STDOUT format. The output now looks like this:

Name             Age
----             ---
John             30  
Jane             25

Perl formats can be a powerful tool for producing well-formatted and readable text output from your scripts. However, they are somewhat outdated and have been largely replaced by more modern output formatting tools such as the printf and sprintf functions.