format
format NAME =
picture line
value list
...
.This function declares a named sequence of picture lines (with
associated values) for use by the write function. If
NAME is omitted, the name defaults to
STDOUT, which happens to be the
default format name for the STDOUT
filehandle. Since, like a sub
declaration, this is a package-global declaration that happens at
compile time, any variables used in the value list need to be visible at
the point of the format’s declaration. That is, lexically scoped
variables must be declared earlier in the file, while dynamically scoped
variables merely need to be set at the time write is called. Here’s an example (which
assumes we’ve already calculated $cost and $quantity):
my $str = "widget"; # Lexically scoped variable
format Nice_Output =
Test: @<<<<<<<< @||||| @>>>>>
$str, $%, '$' . int($num)
.
local $~ = "Nice_Output"; # Select our format
local $num = $cost * $quantity; # Dynamically scoped variable
write;Like filehandles, format names are identifiers that exist in a
symbol table (package) and may be fully qualified by package name.
Within the typeglobs of a symbol table’s entries, formats reside in
their own namespace, which is distinct from filehandles, directory
handles, scalars, arrays, hashes, and subroutines. Like those other six
types, however, a format named Whatever would also be affected by a local on the *Whatever typeglob. In other words, a format is just another gadget contained in a typeglob, independent of the other gadgets. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access