Richard Smith Richard Smith - 1 month ago 6
Perl Question

Two perl formats on a page

I have inherited perl code that uses formats twice in rapid succession. Here's a MWE.

#!/usr/bin/perl

use FileHandle;
use strict;
use warnings;

sub table {
my ($name, $val);

format_name STDOUT "FMT1";
format_top_name STDOUT "FMT1_TOP";

($name, $val) = ("Item1", 42); write;
($name, $val) = ("Item2", 100); write;

format FMT1_TOP =
Name | Cost
-------------+-------
.

format FMT1 =
@>>>>>>>>>>> | @<<<<
$name, $val
.
}

print "Data 1\n"; table; print "\n";
print "Data 2\n"; table;


The problem I'm seeing is that perl obviously thinks both sets of data are part of the same table and doesn't print a new table heading. So the output I get is this:

Data 1
Name | Cost
-------------+-------
Item1 | 42
Item2 | 100

Data 2
Item1 | 42
Item2 | 100


I expected to see:

Data 1
Name | Cost
-------------+-------
Item1 | 42
Item2 | 100

Data 2
Name | Cost
-------------+-------
Item1 | 42
Item2 | 100


I'm sure there must be some
close_format
-like function that I'm missing at the end of
table()
, but formats are so last century that I've forgotten what I once knew about them, and all the examples I can find online use just a single format per program. What am I missing?

Note that replacing formats with something else is not a viable option in this project at this particular point.

Answer

_TOP is a type of page header. Perl interpreter prints it at the top of filehandle.

Use $~ to tell the Perl interpreter that FMT1_TOP is the print format that should be used when calling write.

#!/usr/bin/perl

use FileHandle;
use strict;
use warnings;

sub table {
    my ($name, $val);

$~ = "FMT1_TOP";
write;
    format_name STDOUT "FMT1";
    format_top_name STDOUT "FMT1_TOP";
    ($name, $val) = ("Item1", 42);  write;
    ($name, $val) = ("Item2", 100);  write;

format FMT1_TOP =
Name         | Cost
-------------+-------
.

format FMT1 =
@>>>>>>>>>>> | @<<<<
$name,         $val
.
}

print "Data 1\n"; table; print "\n";
print "Data 2\n"; table;
Comments