{
    "mode": "perldoc",
    "parameter": "perlform",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/perlform/json",
    "generated": "2026-06-03T04:25:12Z",
    "sections": {
        "NAME": {
            "content": "perlform - Perl formats\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "Perl has a mechanism to help you generate simple reports and charts. To facilitate this, Perl\nhelps you code up your output page close to how it will look when it's printed. It can keep\ntrack of things like how many lines are on a page, what page you're on, when to print page\nheaders, etc. Keywords are borrowed from FORTRAN: format() to declare and write() to execute;\nsee their entries in perlfunc. Fortunately, the layout is much more legible, more like BASIC's\nPRINT USING statement. Think of it as a poor man's nroff(1).\n\nFormats, like packages and subroutines, are declared rather than executed, so they may occur at\nany point in your program. (Usually it's best to keep them all together though.) They have their\nown namespace apart from all the other \"types\" in Perl. This means that if you have a function\nnamed \"Foo\", it is not the same thing as having a format named \"Foo\". However, the default name\nfor the format associated with a given filehandle is the same as the name of the filehandle.\nThus, the default format for STDOUT is named \"STDOUT\", and the default format for filehandle\nTEMP is named \"TEMP\". They just look the same. They aren't.\n\nOutput record formats are declared as follows:\n\nformat NAME =\nFORMLIST\n.\n\nIf the name is omitted, format \"STDOUT\" is defined. A single \".\" in column 1 is used to\nterminate a format. FORMLIST consists of a sequence of lines, each of which may be one of three\ntypes:\n\n1.  A comment, indicated by putting a '#' in the first column.\n\n2.  A \"picture\" line giving the format for one output line.\n\n3.  An argument line supplying values to plug into the previous picture line.\n\nPicture lines contain output field definitions, intermingled with literal text. These lines do\nnot undergo any kind of variable interpolation. Field definitions are made up from a set of\ncharacters, for starting and extending a field to its desired width. This is the complete set of\ncharacters for field definitions:\n\n@    start of regular field\n^    start of special field\n<    pad character for left justification\n|    pad character for centering\n>    pad character for right justification\n#    pad character for a right-justified numeric field\n0    instead of first #: pad number with leading zeroes\n.    decimal point within a numeric field\n...  terminate a text field, show \"...\" as truncation evidence\n@*   variable width field for a multi-line value\n^*   variable width field for next line of a multi-line value\n~    suppress line with all fields empty\n~~   repeat line until all fields are exhausted\n\nEach field in a picture line starts with either \"@\" (at) or \"^\" (caret), indicating what we'll\ncall, respectively, a \"regular\" or \"special\" field. The choice of pad characters determines\nwhether a field is textual or numeric. The tilde operators are not part of a field. Let's look\nat the various possibilities in detail.\n",
            "subsections": [
                {
                    "name": "Text Fields",
                    "content": "The length of the field is supplied by padding out the field with multiple \"<\", \">\", or \"|\"\ncharacters to specify a non-numeric field with, respectively, left justification, right\njustification, or centering. For a regular field, the value (up to the first newline) is taken\nand printed according to the selected justification, truncating excess characters. If you\nterminate a text field with \"...\", three dots will be shown if the value is truncated. A special\ntext field may be used to do rudimentary multi-line text block filling; see \"Using Fill Mode\"\nfor details.\n\nExample:\nformat STDOUT =\n@<<<<<<   @||||||   @>>>>>>\n\"left\",   \"middle\", \"right\"\n.\nOutput:\nleft      middle    right\n"
                },
                {
                    "name": "Numeric Fields",
                    "content": "Using \"#\" as a padding character specifies a numeric field, with right justification. An\noptional \".\" defines the position of the decimal point. With a \"0\" (zero) instead of the first\n\"#\", the formatted number will be padded with leading zeroes if necessary. A special numeric\nfield is blanked out if the value is undefined. If the resulting value would exceed the width\nspecified the field is filled with \"#\" as overflow evidence.\n\nExample:\nformat STDOUT =\n@###   @.###   @##.###  @###   @###   ^####\n42,   3.1415,  undef,    0, 10000,   undef\n.\nOutput:\n42   3.142     0.000     0   ####\n\nThe Field @* for Variable-Width Multi-Line Text\nThe field \"@*\" can be used for printing multi-line, nontruncated values; it should (but need\nnot) appear by itself on a line. A final line feed is chomped off, but all other characters are\nemitted verbatim.\n\nThe Field ^* for Variable-Width One-line-at-a-time Text\nLike \"@*\", this is a variable-width field. The value supplied must be a scalar variable. Perl\nputs the first line (up to the first \"\\n\") of the text into the field, and then chops off the\nfront of the string so that the next time the variable is referenced, more of the text can be\nprinted. The variable will *not* be restored.\n\nExample:\n$text = \"line 1\\nline 2\\nline 3\";\nformat STDOUT =\nText: ^*\n$text\n~~    ^*\n$text\n.\nOutput:\nText: line 1\nline 2\nline 3\n"
                },
                {
                    "name": "Specifying Values",
                    "content": "The values are specified on the following format line in the same order as the picture fields.\nThe expressions providing the values must be separated by commas. They are all evaluated in a\nlist context before the line is processed, so a single list expression could produce multiple\nlist elements. The expressions may be spread out to more than one line if enclosed in braces. If\nso, the opening brace must be the first token on the first line. If an expression evaluates to a\nnumber with a decimal part, and if the corresponding picture specifies that the decimal part\nshould appear in the output (that is, any picture except multiple \"#\" characters without an\nembedded \".\"), the character used for the decimal point is determined by the current LCNUMERIC\nlocale if \"use locale\" is in effect. This means that, if, for example, the run-time environment\nhappens to specify a German locale, \",\" will be used instead of the default \".\". See perllocale\nand \"WARNINGS\" for more information.\n"
                },
                {
                    "name": "Using Fill Mode",
                    "content": "On text fields the caret enables a kind of fill mode. Instead of an arbitrary expression, the\nvalue supplied must be a scalar variable that contains a text string. Perl puts the next portion\nof the text into the field, and then chops off the front of the string so that the next time the\nvariable is referenced, more of the text can be printed. (Yes, this means that the variable\nitself is altered during execution of the write() call, and is not restored.) The next portion\nof text is determined by a crude line-breaking algorithm. You may use the carriage return\ncharacter (\"\\r\") to force a line break. You can change which characters are legal to break on by\nchanging the variable $: (that's $FORMATLINEBREAKCHARACTERS if you're using the English\nmodule) to a list of the desired characters.\n\nNormally you would use a sequence of fields in a vertical stack associated with the same scalar\nvariable to print out a block of text. You might wish to end the final field with the text\n\"...\", which will appear in the output if the text was too long to appear in its entirety.\n"
                },
                {
                    "name": "Suppressing Lines Where All Fields Are Void",
                    "content": "Using caret fields can produce lines where all fields are blank. You can suppress such lines by\nputting a \"~\" (tilde) character anywhere in the line. The tilde will be translated to a space\nupon output.\n"
                },
                {
                    "name": "Repeating Format Lines",
                    "content": "If you put two contiguous tilde characters \"~~\" anywhere into a line, the line will be repeated\nuntil all the fields on the line are exhausted, i.e. undefined. For special (caret) text fields\nthis will occur sooner or later, but if you use a text field of the at variety, the expression\nyou supply had better not give the same value every time forever! (\"shift(@f)\" is a simple\nexample that would work.) Don't use a regular (at) numeric field in such lines, because it will\nnever go blank.\n"
                },
                {
                    "name": "Top of Form Processing",
                    "content": "Top-of-form processing is by default handled by a format with the same name as the current\nfilehandle with \"TOP\" concatenated to it. It's triggered at the top of each page. See \"write\"\nin perlfunc.\n\nExamples:\n\n# a report on the /etc/passwd file\nformat STDOUTTOP =\nPasswd File\nName                Login    Office   Uid   Gid Home\n------------------------------------------------------------------\n.\nformat STDOUT =\n@<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<\n$name,              $login,  $office,$uid,$gid, $home\n.\n\n\n# a report from a bug report form\nformat STDOUTTOP =\nBug Reports\n@<<<<<<<<<<<<<<<<<<<<<<<     @|||         @>>>>>>>>>>>>>>>>>>>>>>>\n$system,                      $%,         $date\n------------------------------------------------------------------\n.\nformat STDOUT =\nSubject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n$subject\nIndex: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n$index,                       $description\nPriority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n$priority,        $date,   $description\nFrom: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n$from,                         $description\nAssigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n$programmer,            $description\n~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n$description\n~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n$description\n~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n$description\n~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n$description\n~                                    ^<<<<<<<<<<<<<<<<<<<<<<<...\n$description\n.\n\nIt is possible to intermix print()s with write()s on the same output channel, but you'll have to\nhandle $- ($FORMATLINESLEFT) yourself.\n"
                },
                {
                    "name": "Format Variables",
                    "content": "The current format name is stored in the variable $~ ($FORMATNAME), and the current top of form\nformat name is in $^ ($FORMATTOPNAME). The current output page number is stored in $%\n($FORMATPAGENUMBER), and the number of lines on the page is in $= ($FORMATLINESPERPAGE).\nWhether to autoflush output on this handle is stored in $| ($OUTPUTAUTOFLUSH). The string\noutput before each top of page (except the first) is stored in $^L ($FORMATFORMFEED). These\nvariables are set on a per-filehandle basis, so you'll need to select() into a different one to\naffect them:\n\nselect((select(OUTF),\n$~ = \"MyOtherFormat\",\n$^ = \"MyTopFormat\"\n)[0]);\n\nPretty ugly, eh? It's a common idiom though, so don't be too surprised when you see it. You can\nat least use a temporary variable to hold the previous filehandle: (this is a much better\napproach in general, because not only does legibility improve, you now have an intermediary\nstage in the expression to single-step the debugger through):\n\n$ofh = select(OUTF);\n$~ = \"MyOtherFormat\";\n$^ = \"MyTopFormat\";\nselect($ofh);\n\nIf you use the English module, you can even read the variable names:\n\nuse English;\n$ofh = select(OUTF);\n$FORMATNAME     = \"MyOtherFormat\";\n$FORMATTOPNAME = \"MyTopFormat\";\nselect($ofh);\n\nBut you still have those funny select()s. So just use the FileHandle module. Now, you can access\nthese special variables using lowercase method names instead:\n\nuse FileHandle;\nformatname     OUTF \"MyOtherFormat\";\nformattopname OUTF \"MyTopFormat\";\n\nMuch better!\n"
                }
            ]
        },
        "NOTES": {
            "content": "Because the values line may contain arbitrary expressions (for at fields, not caret fields), you\ncan farm out more sophisticated processing to other functions, like sprintf() or one of your\nown. For example:\n\nformat Ident =\n@<<<<<<<<<<<<<<<\n&commify($n)\n.\n\nTo get a real at or caret into the field, do this:\n\nformat Ident =\nI have an @ here.\n\"@\"\n.\n\nTo center a whole line of text, do something like this:\n\nformat Ident =\n@|||||||||||||||||||||||||||||||||||||||||||||||\n\"Some text line\"\n.\n\nThere is no builtin way to say \"float this to the right hand side of the page, however wide it\nis.\" You have to specify where it goes. The truly desperate can generate their own format on the\nfly, based on the current number of columns, and then eval() it:\n\n$format  = \"format STDOUT = \\n\"\n. '^' . '<' x $cols . \"\\n\"\n. '$entry' . \"\\n\"\n. \"\\t^\" . \"<\" x ($cols-8) . \"~~\\n\"\n. '$entry' . \"\\n\"\n. \".\\n\";\nprint $format if $Debugging;\neval $format;\ndie $@ if $@;\n\nWhich would generate a format looking something like this:\n\nformat STDOUT =\n^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n$entry\n^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~~\n$entry\n.\n\nHere's a little program that's somewhat like fmt(1):\n\nformat =\n^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~\n$\n\n.\n\n$/ = '';\nwhile (<>) {\ns/\\s*\\n\\s*/ /g;\nwrite;\n}\n",
            "subsections": [
                {
                    "name": "Footers",
                    "content": "While $FORMATTOPNAME contains the name of the current header format, there is no corresponding\nmechanism to automatically do the same thing for a footer. Not knowing how big a format is going\nto be until you evaluate it is one of the major problems. It's on the TODO list.\n\nHere's one strategy: If you have a fixed-size footer, you can get footers by checking\n$FORMATLINESLEFT before each write() and print the footer yourself if necessary.\n\nHere's another strategy: Open a pipe to yourself, using \"open(MYSELF, \"|-\")\" (see \"open\" in\nperlfunc) and always write() to MYSELF instead of STDOUT. Have your child process massage its\nSTDIN to rearrange headers and footers however you like. Not very convenient, but doable.\n"
                },
                {
                    "name": "Accessing Formatting Internals",
                    "content": "For low-level access to the formatting mechanism, you may use formline() and access $^A (the\n$ACCUMULATOR variable) directly.\n\nFor example:\n\n$str = formline <<'END', 1,2,3;\n@<<<  @|||  @>>>\nEND\n\nprint \"Wow, I just stored '$^A' in the accumulator!\\n\";\n\nOr to make an swrite() subroutine, which is to write() what sprintf() is to printf(), do this:\n\nuse Carp;\nsub swrite {\ncroak \"usage: swrite PICTURE ARGS\" unless @;\nmy $format = shift;\n$^A = \"\";\nformline($format,@);\nreturn $^A;\n}\n\n$string = swrite(<<'END', 1, 2, 3);\nCheck me out\n@<<<  @|||  @>>>\nEND\nprint $string;\n"
                }
            ]
        },
        "WARNINGS": {
            "content": "The lone dot that ends a format can also prematurely end a mail message passing through a\nmisconfigured Internet mailer (and based on experience, such misconfiguration is the rule, not\nthe exception). So when sending format code through mail, you should indent it so that the\nformat-ending dot is not on the left margin; this will prevent SMTP cutoff.\n\nLexical variables (declared with \"my\") are not visible within a format unless the format is\ndeclared within the scope of the lexical variable.\n\nIf a program's environment specifies an LCNUMERIC locale and \"use locale\" is in effect when the\nformat is declared, the locale is used to specify the decimal point character in formatted\noutput. Formatted output cannot be controlled by \"use locale\" at the time when write() is\ncalled. See perllocale for further discussion of locale handling.\n\nWithin strings that are to be displayed in a fixed-length text field, each control character is\nsubstituted by a space. (But remember the special meaning of \"\\r\" when using fill mode.) This is\ndone to avoid misalignment when control characters \"disappear\" on some output media.\n",
            "subsections": []
        }
    },
    "summary": "perlform - Perl formats",
    "flags": [],
    "examples": [],
    "see_also": []
}