PERLFORM(1perl)
๐ perlform โ Perl Programmers Reference Guide
okay bestie, gather round, because this is PERLFORM(1perl) and it's genuinely one of the most aesthetic corners of Perl?? Like, you get to draw your output with little pictures. Obsessed.
๐ NAME ๐
perlform โ Perl formats
โจ DESCRIPTION โจ
okay so Perl has a whole mechanism to help you generate simple reports and charts. The whole idea? Perl lets you code up your output page close to how it will actually look when it's printed. It can keep track of stuff like how many lines are on a page, what page you're on, when to print page headers, etc. The keywords are borrowed straight from FORTRAN: format() to declare and write() to execute โ go check their entries in perlfunc. But luckily the layout is much more legible, more like BASIC's PRINT USING statement. Think of it as a poor man's nroff(1). ๐
Formats, like packages and subroutines, are declared rather than executed, so they may occur at any point in your program. (Usually it's best to keep them all together though.) They have their own namespace, completely apart from all the other "types" in Perl. This means that if you have a function named "Foo", it is not the same thing as having a format named "Foo". However โ plot twist โ the default name for the format associated with a given filehandle is the same as the name of the filehandle. So the default format for STDOUT is named "STDOUT", and the default format for filehandle TEMP is named "TEMP". They just look the same. They aren't. ๐
Output record formats are declared like this:
format NAME =
FORMLIST
.
If the name is omitted, format "STDOUT" is defined. A single . in column 1 is what terminates a format. FORMLIST is a sequence of lines, and each one can be one of three types:
- A comment, indicated by putting a
'#'in the first column. - A "picture" line giving the format for one output line.
- An argument line supplying values to plug into the previous picture line.
Picture lines contain output field definitions, intermingled with literal text. These lines do not undergo any kind of variable interpolation. Field definitions are made up from a set of characters, for starting and extending a field to its desired width. Here's the complete set of characters for field definitions:
@โ start of regular field^โ start of special field<โ pad character for left justification|โ pad character for centering>โ pad character for right justification#โ pad character for a right-justified numeric field0โ instead of first#: pad number with leading zeroes.โ decimal point within a numeric field...โ terminate a text field, show"..."as truncation evidence@*โ variable width field for a multi-line value^*โ variable width field for next line of a multi-line value~โ suppress line with all fields empty~~โ repeat line until all fields are exhausted
Each field in a picture line starts with either @ (at) or ^ (caret), indicating what we'll call, respectively, a "regular" or "special" field. The choice of pad characters determines whether a field is textual or numeric. The tilde operators are not part of a field. Let's look at the various possibilities in detail, bestie. ๐ซถ
๐ธ Text Fields
The length of the field is supplied by padding out the field with multiple <, >, or | characters to specify a non-numeric field with, respectively, left justification, right justification, or centering. For a regular field, the value (up to the first newline) is taken and printed according to the selected justification, truncating excess characters. If you terminate a text field with ..., three dots will be shown if the value is truncated. A special text field may be used to do rudimentary multi-line text block filling; see "Using Fill Mode" for details.
Example:
Example:
format STDOUT =
@<<<<<< @|||||| @>>>>>>
"left", "middle", "right"
.
Output:
left middle right
๐ Numeric Fields
Using # as a padding character specifies a numeric field, with right justification. An optional . defines the position of the decimal point. With a 0 (zero) instead of the first #, the formatted number will be padded with leading zeroes if necessary. A special numeric field is blanked out if the value is undefined. If the resulting value would exceed the width specified, the field is filled with # as overflow evidence. ๐
Example:
Example:
format STDOUT =
@### @.### @##.### @### @### ^####
42, 3.1415, undef, 0, 10000, undef
.
Output:
42 3.142 0.000 0 ####
๐ฆ The Field @* for Variable-Width Multi-Line Text
The field "@*" can be used for printing multi-line, nontruncated values; it should (but need not) appear by itself on a line. A final line feed is chomped off, but all other characters are emitted verbatim.
๐ The Field ^* for Variable-Width One-line-at-a-time Text
Like "@*", this is a variable-width field. The value supplied must be a scalar variable. Perl puts the first line (up to the first "\n") of the text into the field, and then chops off the front of the string so that the next time the variable is referenced, more of the text can be printed. The variable will not be restored. ๐ญ
Example:
Example:
$text = "line 1\nline 2\nline 3";
format STDOUT =
Text: ^*
$text
~~ ^*
$text
.
Output:
Text: line 1
line 2
line 3
๐ Specifying Values
The values are specified on the following format line in the same order as the picture fields. The expressions providing the values must be separated by commas. They are all evaluated in a list context before the line is processed, so a single list expression could produce multiple list elements. The expressions may be spread out to more than one line if enclosed in braces. If so, the opening brace must be the first token on the first line. If an expression evaluates to a number with a decimal part, and if the corresponding picture specifies that the decimal part should appear in the output (that is, any picture except multiple # characters without an embedded .), the character used for the decimal point is determined by the current LC_NUMERIC locale if use locale is in effect. This means that, if, for example, the run-time environment happens to specify a German locale, "," will be used instead of the default ".". See perllocale and "WARNINGS" for more information.
๐ Using Fill Mode
On text fields the caret enables a kind of fill mode. Instead of an arbitrary expression, the value supplied must be a scalar variable that contains a text string. Perl puts the next portion of the text into the field, and then chops off the front of the string so that the next time the variable is referenced, more of the text can be printed. (Yes, this means that the variable itself is altered during execution of the write() call, and is not restored.) The next portion of text is determined by a crude line-breaking algorithm. You may use the carriage return character ("\r") to force a line break. You can change which characters are legal to break on by changing the variable $: (that's $FORMAT_LINE_BREAK_CHARACTERS if you're using the English module) to a list of the desired characters.
Normally you would use a sequence of fields in a vertical stack associated with the same scalar variable to print out a block of text. You might wish to end the final field with the text "...", which will appear in the output if the text was too long to appear in its entirety.
โญ Suppressing Lines Where All Fields Are Void
Using caret fields can produce lines where all fields are blank. You can suppress such lines by putting a "~" (tilde) character anywhere in the line. The tilde will be translated to a space upon output.
๐ฅ Repeating Format Lines
If you put two contiguous tilde characters "~~" anywhere into a line, then in addition to suppressing the line if all fields are blank, the line will be repeated until all the fields on the line are exhausted, i.e. undefined. For special (caret) text fields this will occur sooner or later, but if you use a text field of the at variety, the expression you supply had better not give the same value every time forever! (shift(@f) is a simple example that would work.) Don't use a regular (at) numeric field in such lines, because it will never go blank.
๐ง Top of Form Processing
Top-of-form processing is by default handled by a format with the same name as the current filehandle with "_TOP" concatenated to it. It's triggered at the top of each page. See "write" in perlfunc.
Examples:
# a report on the /etc/passwd file
format STDOUT_TOP =
Passwd File
Name Login Office Uid Gid Home
------------------------------------------------------------------
.
format STDOUT =
@<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
$name, $login, $office,$uid,$gid, $home
.
# a report from a bug report form
format STDOUT_TOP =
Bug Reports
@<<<<<<<<<<<<<<<<<<<<<<< @||| @>>>>>>>>>>>>>>>>>>>>>>>
$system, $%, $date
------------------------------------------------------------------
.
format STDOUT =
Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$subject
Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$index, $description
Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$priority, $date, $description
From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$from, $description
Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$programmer, $description
~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$description
~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$description
~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$description
~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$description
~ ^<<<<<<<<<<<<<<<<<<<<<<<...
$description
.
It is possible to intermix print()s with write()s on the same output channel, but you'll have to handle "$-" ($FORMAT_LINES_LEFT) yourself. ๐
no cap, that last bit is the one that bites people โ if you're mixingprint()andwrite()on the same channel, the format bookkeeping is your problem now. ๐ซ
โจ Format Variables โจ
okay so bestie, the format name you're currently living in is stashed in $~ (aka $FORMAT_NAME), and the name of the current top of form format is hanging out in $^ ($FORMAT_TOP_NAME). the page number you're on rn? that's $% ($FORMAT_PAGE_NUMBER). how many lines fit on a page? $= ($FORMAT_LINES_PER_PAGE). whether to autoflush output on the handle is in $| ($OUTPUT_AUTOFLUSH). and the string that gets printed before every top of page (every one except the first) lives in $^L ($FORMAT_FORMFEED). ๐
here's the catch though โ these variables are all set per-filehandle, so if you wanna change them you gotta select() into a different one:
select((select(OUTF),
$~ = "My_Other_Format",
$^ = "My_Top_Format"
)[0]);
pretty gnarly, right? ๐ญ but it's a super common idiom so don't be shook when you see it. you can at least stash the previous filehandle in a temp variable (and honestly this is the better move in general, because not only is it more readable, you also get an intermediate stage in the expression so you can single-step it through the debugger):
$ofh = select(OUTF);
$~ = "My_Other_Format";
$^ = "My_Top_Format";
select($ofh);
and if you load up the English module, the variable names actually say words:
use English;
$ofh = select(OUTF);
$FORMAT_NAME = "My_Other_Format";
$FORMAT_TOP_NAME = "My_Top_Format";
select($ofh);
but you've still got those silly select()s tho. so literally just use the FileHandle module instead โ then you can reach these special variables through lowercase method names:
use FileHandle;
format_name OUTF "My_Other_Format";
format_top_name OUTF "My_Top_Format";
so much better, no cap ๐
โจ NOTES โจ
because the values line can hold arbitrary expressions (this is for @ fields, not caret fields!), you can outsource the fancy processing to other functions โ like sprintf() or one of your own. for example:
format Ident =
@<<<<<<<<<<<<<<<<
&commify($n)
.
if you want a literal actual at-sign or caret to show up inside the field, do it like this:
format Ident =
I have an @ here.
"@"
.
and to center a whole entire line of text, it's giving something like:
format Ident =
@|||||||||||||||||||||||||||||||||||||||||||||||
"Some text line"
.
ngl there is no builtin way to say "hey, float this over to the right-hand side of the page, however wide that page happens to be." you have to say exactly where it goes. the truly desperate among us can generate their own format on the fly, based on the current number of columns, and then eval() it:
$format = "format STDOUT = \n"
. '^' . '<' x $cols . "\n"
. '$entry' . "\n"
. "\t^" . "<" x ($cols-8) . "~~\n"
. '$entry' . "\n"
. ".\n";
print $format if $Debugging;
eval $format;
die $@ if $@;
which would cook up a format looking kinda like this:
format STDOUT =
^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$entry
^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
$entry
.
and here's a little program that's lowkey like fmt(1):
format =
^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~
$_
.
$/ = '';
while (<>) {
s/\s*\n\s*/ /g;
write;
}
๐ฆ Footers ๐ฆ
so $FORMAT_TOP_NAME is out here holding the name of the current header format, but there's no matching mechanism that automatically does the same thing for a footer. ๐ one of the big problems is that you just don't know how big a format is gonna be until you actually evaluate it. it's on the TODO list, bestie, it's on the list.
here's one strategy: if your footer is a fixed size, you can get footers by checking $FORMAT_LINES_LEFT before every write() and just print the footer yourself when you need to.
here's another strategy: open a pipe to yourself with open(MYSELF, "|-") (peep "open" in perlfunc), and always write() to MYSELF instead of STDOUT. then your child process can massage its STDIN to rearrange headers and footers however it wants. not super convenient, but doable fr.
๐ฎ Accessing Formatting Internals ๐ฎ
for low-level access to the formatting machinery, you can use formline() and touch $^A (the $ACCUMULATOR variable) directly.
for example:
$str = formline <<'END', 1,2,3;
@<<< @||| @>>>
END
print "Wow, I just stored '$^A' in the accumulator!\n";
or, to make an swrite() subroutine โ which is to write() what sprintf() is to printf() โ do this:
use Carp;
sub swrite {
croak "usage: swrite PICTURE ARGS" unless @_;
my $format = shift;
$^A = "";
formline($format,@_);
return $^A;
}
$string = swrite(<<'END', 1, 2, 3);
Check me out
@<<< @||| @>>>
END
print $string;
โ ๏ธ WARNINGS โ ๏ธ
bestie listen โ that lone dot that ends a format can also prematurely end a mail message passing through a misconfigured Internet mailer. and based on experience? that kind of misconfiguration is the rule, not the exception. ๐ so when you're sending format code through mail, indent it so that format-ending dot is not sitting on the left margin. that'll stop SMTP from cutting you off.
lexical variables (the ones you declare with my) are not visible inside a format โ unless the format itself is declared within the scope of that lexical variable.
if a program's environment specifies an LC_NUMERIC locale, and "use locale" is in effect back when the format is declared, then the locale gets used to specify the decimal point character in formatted output. and heads up: formatted output cannot be controlled by "use locale" at the time write() is called. see perllocale for more on locale handling.
and inside strings that are gonna be displayed in a fixed-length text field, every single control character gets substituted by a space. (but remember the special meaning of "\r" when you're using fill mode!) this is done so nothing gets misaligned when control characters "disappear" on certain output media.
and that's a wrap, bestie ๐ซถ this was perl v5.44.0, dated 2026-10-17 โ go write some formats and absolutely slay ๐โจ๐
๐ฆ where this page comes from
- arch rolling: perl 5.44.0-1 ยท Artistic-1.0-Perl AND GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms