Text::Reform(3pm)

πŸ’… NAME πŸ’…

Text::Reform β€” Manual text wrapping and reformatting. Okay bestie, this is the manual page for Text::Reform (manual name, iykyk), and it's literally about manual text wrapping and reformatting. No cap. ✨

πŸŽ€ VERSION πŸŽ€

This document describes version 1.20 of Text::Reform, released 2009-09-06. Yes, it's an oldie but a goodie. πŸ’–

🌈 SYNOPSIS 🌈

use Text::Reform;

print form $template,
           $data, $to, $fill, $it, $with;

use Text::Reform qw( tag );

print tag 'B', $enboldened_text;

πŸ¦‹ DESCRIPTION πŸ¦‹

✨ The form sub ✨

Okay so the form() subroutine may be exported from the module. It takes a series of format (or "picture") strings followed by replacement values, interpolates those values into each picture string, and returns the result. The effect is similar to the inbuilt perl format mechanism, although the field specification syntax is simpler and some of the formatting behaviour is more sophisticated. Slay. πŸ’…

A picture string consists of sequences of the following characters:

  • < β€” Left-justified field indicator. A series of two or more sequential <'s specify a left-justified field to be filled by a subsequent value. A single < is formatted as the literal character <.
  • > β€” Right-justified field indicator. A series of two or more sequential >'s specify a right-justified field to be filled by a subsequent value. A single > is formatted as the literal character >.
  • <<<>>> β€” Fully-justified field indicator. Field may be of any width, and brackets need not balance, but there must be at least 2 < and 2 >.
  • ^ β€” Centre-justified field indicator. A series of two or more sequential ^'s specify a centred field to be filled by a subsequent value. A single ^ is formatted as the literal character ^.
  • >>>.<<<< β€” A numerically formatted field with the specified number of digits to either side of the decimal place. See "Numerical formatting" below.
  • [ β€” Left-justified block field indicator. Just like a < field, except it repeats as required on subsequent lines. See below. A single [ is formatted as the literal character [.
  • ] β€” Right-justified block field indicator. Just like a > field, except it repeats as required on subsequent lines. See below. A single ] is formatted as the literal character ].
  • [[[]]] β€” Fully-justified block field indicator. Just like a <<<>>> field, except it repeats as required on subsequent lines. See below. Field may be of any width, and brackets need not balance, but there must be at least 2 [ and 2 ].
  • | β€” Centre-justified block field indicator. Just like a ^ field, except it repeats as required on subsequent lines. See below. A single | is formatted as the literal character |.
  • ]]].[[[[ β€” A numerically formatted block field with the specified number of digits to either side of the decimal place. Just like a >>>.<<<< field, except it repeats as required on subsequent lines. See below.
  • ~ β€” A one-character wide block field.
  • \ β€” Literal escape of next character (e.g. "\~" is formatted as ~, not a one character wide block field).
  • Any other character β€” That literal character.

Any substitution value which is undef (either explicitly so, or because it is missing) is replaced by an empty string. Periodt. 🫢

🌸 Controlling line filling 🌸

Note that, unlike the a perl format, form preserves whitespace (including newlines) unless called with certain options. Big mood.

The squeeze option (when specified with a true value) causes any sequence of spaces and/or tabs (but not newlines) in an interpolated string to be replaced with a single space.

A true value for the fill option causes (only) newlines to be squeezed.

To minimize all whitespace, you need to specify both options. Hence:

$format = "EG> [[[[[[[[[[[[[[[[[[[[[";
$data   = "h  e\t l lo\nworld\t\t\t\t\t";

print form $format, $data;              # all whitespace preserved:
                                        #
                                        # EG> h  e            l lo
                                        # EG> world

print form {squeeze=>1},                # only newlines preserved:
           $format, $data;              #
                                        # EG> h e l lo
                                        # EG> world

print form {fill=>1},                   # only spaces/tabs preserved:
            $format, $data;             #
                                        # EG> h  e        l lo world

print form {squeeze=>1, fill=>1},       # no whitespace preserved:
           $format, $data;              #
                                        # EG> h e l lo world

Whether or not filling or squeezing is in effect, form can also be directed to trim any extra whitespace from the end of each line it formats, using the trim option. If this option is specified with a true value, every line returned by form will automatically have the substitution s/[ \t]+$//gm applied to it.

Hence:

print length form "[[[[[[[[[[", "short";
# 11

print length form {trim=>1}, "[[[[[[[[[[", "short";
# 6

It is also possible to control the character used to fill lines that are too short, using the 'filler' option. If this option is specified the value of the 'filler' flag is used as the fill string, rather than the default " ".

For example:

print form { filler=>'*' },
        "Pay bearer: ^^^^^^^^^^^^^^^^^^^",
        '$123.45';

prints:

Pay bearer: ******$123.45******

If the filler string is longer than one character, it is truncated to the appropriate length. So:

print form { filler=>'-->' },
        "Pay bearer: ]]]]]]]]]]]]]]]]]]]",
        ['$1234.50', '$123.45', '$12.34'];

prints:

Pay bearer: ->-->-->-->$1234.50
Pay bearer: -->-->-->-->$123.45
Pay bearer: >-->-->-->-->$12.34

If the value of the 'filler' option is a hash, then its 'left' and 'right' entries specify separate filler strings for each side of an interpolated value. So:

print form { filler=>{left=>'->', right=>'*'} },
        "Pay bearer: <<<<<<<<<<<<<<<<<<",
        '$123.45',
        "Pay bearer: >>>>>>>>>>>>>>>>>>",
        '$123.45',
        "Pay bearer: ^^^^^^^^^^^^^^^^^^",
        '$123.45';

prints:

Pay bearer: $123.45***********
Pay bearer: >->->->->->$123.45
Pay bearer: >->->$123.45******

πŸ’œ Temporary and permanent default options πŸ’œ

If form is called with options, but no template string or data, it resets its defaults to the options specified. If called in a void context:

form { squeeze => 1, trim => 1 };

the options become permanent defaults.

However, when called with only options in non-void context, form resets its defaults to those options and returns an object. The reset default values persist only until that returned object is destroyed. Hence to temporarily reset form's defaults within a single subroutine:

sub single {
        my $tmp = form { squeeze => 1, trim => 1 };

        # do formatting with the obove defaults

} # form's defaults revert to previous values as $tmp object destroyed

🧚 Multi-line format specifiers and interleaving 🧚

By default, if a format specifier contains two or more lines (i.e. one or more newline characters), the entire format specifier is repeatedly filled as a unit, until all block fields have consumed their corresponding arguments. For example, to build a simple look-up table:

my @values   = (1..12);

my @squares  = map { sprintf "%.6g", $_**2    } @values;
my @roots    = map { sprintf "%.6g", sqrt($_) } @values;
my @logs     = map { sprintf "%.6g", log($_)  } @values;
my @inverses = map { sprintf "%.6g", 1/$_     } @values;

print form
"  N      N**2    sqrt(N)      log(N)      1/N",
"=====================================================",
"| [[  |  [[[  |  [[[[[[[[[[ | [[[[[[[[[ | [[[[[[[[[ |
-----------------------------------------------------",
\@values, \@squares, \@roots, \@logs, \@inverses;

The multiline format specifier:

"| [[  |  [[[  |  [[[[[[[[[[ | [[[[[[[[[ | [[[[[[[[[ |
-----------------------------------------------------",

is treated as a single logical line. So form alternately fills the first physical line (interpolating one value from each of the arrays) and the second physical line (which puts a line of dashes between each row of the table) producing:

  N      N**2    sqrt(N)      log(N)      1/N
=====================================================
| 1   |  1    |  1          | 0         | 1         |
-----------------------------------------------------
| 2   |  4    |  1.41421    | 0.693147  | 0.5       |
-----------------------------------------------------
| 3   |  9    |  1.73205    | 1.09861   | 0.333333  |
-----------------------------------------------------
| 4   |  16   |  2          | 1.38629   | 0.25      |
-----------------------------------------------------
| 5   |  25   |  2.23607    | 1.60944   | 0.2       |
-----------------------------------------------------
| 6   |  36   |  2.44949    | 1.79176   | 0.166667  |
-----------------------------------------------------
| 7   |  49   |  2.64575    | 1.94591   | 0.142857  |
-----------------------------------------------------
| 8   |  64   |  2.82843    | 2.07944   | 0.125     |
-----------------------------------------------------
| 9   |  81   |  3          | 2.19722   | 0.111111  |
-----------------------------------------------------
| 10  |  100  |  3.16228    | 2.30259   | 0.1       |
-----------------------------------------------------
| 11  |  121  |  3.31662    | 2.3979    | 0.0909091 |
-----------------------------------------------------
| 12  |  144  |  3.4641     | 2.48491   | 0.0833333 |
-----------------------------------------------------

This implies that formats and the variables from which they're filled need to be interleaved. That is, a multi-line specification like this:

okay so, picking up that format-string thread: here's the code moment:

print form
"Passed:                      ##
   [[[[[[[[[[[[[[[             # single format specification
Failed:                        # (needs two sets of data)
   [[[[[[[[[[[[[[[",          ##

\@passes, \@fails;            ##  data for previous format

would print:

Passed:
   <pass 1>
Failed:
   <fail 1>
Passed:
   <pass 2>
Failed:
   <fail 2>
Passed:
   <pass 3>
Failed:
   <fail 3>

because the four-line format specifier is treated as a single unit, to be repeatedly filled until all the data in @passes and @fails has been consumed. no cap.

Unlike the table example, where this unit filling correctly put a line of dashes between lines of data, in this case the alternation of passes and fails is probably not the desired effect. πŸ™ˆ

Judging by the labels, it is far more likely that the user wanted:

Passed:
   <pass 1>
   <pass 2>
   <pass 3>
Failed:
   <fail 4>
   <fail 5>
   <fail 6>

To achieve that, either explicitly interleave the formats and their data sources:

print form
"Passed:",               ## single format (no data required)
"   [[[[[[[[[[[[[[[",    ## single format (needs one set of data)
    \@passes,            ## data for previous format
"Failed:",               ## single format (no data required)
"   [[[[[[[[[[[[[[[",    ## single format (needs one set of data)
    \@fails;             ## data for previous format

or instruct form to do it for you automagically, by setting the 'interleave' flag true:

print form {interleave=>1}
"Passed:                 ##
   [[[[[[[[[[[[[[[        # single format
Failed:                   # (needs two sets of data)
   [[[[[[[[[[[[[[[",     ##

                         ## data to be automagically interleaved
\@passes, \@fails;        # as necessary between lines of previous
                         ## format

πŸ’… How form hyphenates πŸ’…

Any line with a block field repeats on subsequent lines until all block fields on that line have consumed all their data. Non-block fields on these lines are replaced by the appropriate number of spaces. periodt.

Words are wrapped whole, unless they will not fit into the field at all, in which case they are broken and (by default) hyphenated. Simple hyphenation is used (i.e. break at the N-1th character and insert a '-'), unless a suitable alternative subroutine is specified instead.

Words will not be broken if the break would leave less than 2 characters on the current line. This minimum can be varied by setting the 'minbreak' option to a numeric value indicating the minimum total broken characters (including hyphens) required on the current line. Note that, for very narrow fields, words will still be broken (but unhyphenated). For example:

print form '~', 'split';

would print:

s
p
l
i
t

whilst:

print form {minbreak=>1}, '~', 'split';

would print:

s-
p-
l-
i-
t

Alternative breaking subroutines can be specified using the "break" option in a configuration hash. For example:

form { break => \&my_line_breaker }
     $format_str,
     @data;

form expects any user-defined line-breaking subroutine to take three arguments (the string to be broken, the maximum permissible length of the initial section, and the total width of the field being filled). The hypenate sub must return a list of two strings: the initial (broken) section of the word, and the remainder of the string respectively).

For example:

sub tilde_break = sub($$$)
{
        (substr($_[0],0,$_[1]-1).'~', substr($_[0],$_[1]-1));
}

form { break => \&tilde_break }
     $format_str,
     @data;

makes '~' the hyphenation character, whilst:

sub wrap_and_slop = sub($$$)
{
        my ($text, $reqlen, $fldlen) = @_;
        if ($reqlen==$fldlen) { $text =~ m/\A(\s*\S*)(.*)/s }
        else                  { ("", $text) }
}

form { break => \&wrap_and_slop }
     $format_str,
     @data;

wraps excessively long words to the next line and "slops" them over the right margin if necessary. 🫢

The Text::Reform package provides three functions to simplify the use of variant hyphenation schemes. The exportable subroutine Text::Reform::break_wrap generates a reference to a subroutine implementing the "wrap-and-slop" algorithm shown in the last example, which could therefore be rewritten:

use Text::Reform qw( form break_wrap );

form { break => break_wrap }
     $format_str,
     @data;

The subroutine Text::Reform::break_with takes a single string argument and returns a reference to a sub which hyphenates by cutting off the text at the right margin and appending the string argument. Hence the first of the two examples could be rewritten:

use Text::Reform qw( form break_with );

form { break => break_with('~') }
     $format_str,
     @data;

The subroutine Text::Reform::break_at takes a single string argument and returns a reference to a sub which hyphenates by breaking immediately after that string. For example:

use Text::Reform qw( form break_at );

form { break => break_at('-') }
       "[[[[[[[[[[[[[[",
       "The Newton-Raphson methodology";

# returns:
#
#       "The Newton-
#        Raphson
#        methodology"

Note that this differs from the behaviour of break_with, which would be:

form { break => break_with('-') }
       "[[[[[[[[[[[[[[",
       "The Newton-Raphson methodology";

# returns:
#
#       "The Newton-R-
#        aphson metho-
#        dology"

Hence break_at is generally a better choice. πŸ‘‘

break_at also takes an 'except' option, which tells the resulting subroutine not to break in the middle of certain strings. For example:

form { break => break_at('-', {except=>qr/Newton-Raphson/}) }
       "[[[[[[[[[[[[[[",
       "The Newton-Raphson methodology";

# returns:
#
#       "The
#        Newton-Raphson
#        methodology"

This option is particularly useful for preserving URLs. πŸ”—

The subroutine Text::Reform::break_TeX returns a reference to a sub which hyphenates using Jan Pazdziora's TeX::Hyphen module. For example:

use Text::Reform qw( form break_wrap );

form { break => break_TeX }
     $format_str,
     @data;

Note that in the previous examples there is no leading '\&' before break_wrap, break_with, or break_TeX, since each is being directly called (and returns a reference to some other suitable subroutine);

✨ The form formatting algorithm ✨

The algorithm form uses is:

  1. If interleaving is specified, split the first string in the argument list into individual format lines and add a terminating newline (unless one is already present). Otherwise, treat the entire string as a single "line" (like /s does in regexes)
  2. For each format line...
    • 2.1. determine the number of fields and shift that many values off the argument list and into the filling list. If insufficient arguments are available, generate as many empty strings as are required.
    • 2.2. generate a text line by filling each field in the format line with the initial contents of the corresponding arg in the filling list (and remove those initial contents from the arg).
    • 2.3. replace any <, >, or ^ fields by an equivalent number of spaces. Splice out the corresponding args from the filling list.
    • 2.4. Repeat from step 2.2 until all args in the filling list are empty.
  3. concatenate the text lines generated in step 2
  4. repeat from step 1 until the argument list is empty

πŸŽ€ form examples πŸŽ€

As an example of the use of form, the following:

$count = 1;
$text = "A big long piece of text to be formatted exquisitely";

print form q
q{       ||||  <<<<<<<<<<   },
$count, $text,
q{       ----------------   },
q{       ^^^^  ]]]]]]]]]]|  },
$count+11, $text,
q{                       =
         ]]].[[[            },
"123 123.4\n123.456789";

produces the following output:

                 1    A big long
                ----------------
                 12     piece of|
                      text to be|
                       formatted|
                      exquisite-|
                              ly|
                                =
                123.0
                                =
                123.4
                                =
                123.456

Note that block fields in a multi-line format string, cause the entire multi-line format to be repeated as often as necessary. πŸ”

Picture strings and replacement values are interleaved in the traditional "format" format, but care is needed to ensure that the correct number of substitution values are provided. Another example:

$report = form
        'Name           Rank    Serial Number',
        '====           ====    =============',
        '<<<<<<<<<<<<<  ^^^^    <<<<<<<<<<<<<',
         $name,         $rank,  $serial_number,
        ''
        'Age    Sex     Description',
        '===    ===     ===========',
        '^^^    ^^^     [[[[[[[[[[[',
         $age,  $sex,   $description;

πŸ¦‹ How form consumes strings πŸ¦‹

Unlike "format", within form non-block fields do consume the text they format, so the following:

...and honestly this is where the main character energy of the whole thing lives, bestie, so pay attention πŸ’…

$text = "a line of text to be formatted over three lines";
print form "<<<<<<<<<<\n  <<<<<<<<\n    <<<<<<\n",
            $text,        $text,        $text;

which gives you:

a line of
  text to
    be fo-

and NOT this:

a line of
  a line
    a line

So if you actually want that second look β€” where every single copy starts fresh from a line of text β€” you gotta turn those variable arguments into independent literals. Double-quoted interpolation is the move:

$text = "a line of text to be formatted over three lines";
print form "<<<<<<<<<<\n  <<<<<<<<\n    <<<<\n",
           "$text",      "$text",      "$text";

Ok so here's a lil detail that lowkey matters: even though the values you pass in as variable arguments get progressively consumed inside form, the actual values of the original variables you passed are not altered. Not a scratch on 'em. Hence:

$text = "a line of text to be formatted over three lines";
print form "<<<<<<<<<<\n  <<<<<<<<\n    <<<<\n",
            $text,        $text,        $text;
print $text, "\n";

will print:

a line of
  text to
    be fo-
a line of text to be formatted over three lines

See? $text came out the other side completely untouched 🫢

But if you want form to actually consume the values of the original variables you passed, then pass them as references. Like so:

$text = "a line of text to be formatted over three lines";
print form "<<<<<<<<<<\n  <<<<<<<<\n    <<<<\n",
            \$text,       \$text,       \$text;
print $text, "\n";

will print:

a line of
  text to
    be fo-
rmatted over three lines

(yes, the fo- plus rmatted β€” that's not a typo, that's literally what happens when the first pass eats into it 😭)

⚠️ Safety check, bestie: the "non-consuming" behaviour takes precedence. So if some variable gets passed to form both by reference and by value, its final value will be unchanged. Periodt.

✨ Numerical formatting ✨

The >>>.<<< and ]]].[[[ field specifiers can format numeric values around a fixed decimal place marker. Iconic, honestly. Example:

print form '(]]]]].[[)', <<EONUMS;
           1
           1.0
           1.001
           1.009
           123.456
           1234567
           one two
EONUMS

would print:

(    1.0 )
(    1.0 )
(    1.00)
(    1.01)
(  123.46)
(#####.##)
(?????.??)
(?????.??)

So fractions get rounded to however many places you asked for after the decimal, but only the significant digits show. That's literally why, up in that example, 1 and 1.0 come out as 1.0 while 1.001 comes out as 1.00. Slay πŸ’–

You can also demand that the maximal number of decimal places is always used β€” just give the configuration option numeric a value that matches /\bAllPlaces\b/i. For example:

print form { numeric => AllPlaces },
           '(]]]]].[[)', <<'EONUMS';
           1
           1.0
EONUMS

would print:

(    1.00)
(    1.00)

Ok and a heads up: even though decimal digits get rounded to fit the width you specified, the integral part of a number is never modified. Like, ever. And if there aren't enough places before the decimal place to represent the number, the entire number gets replaced with hashes. Bye πŸ‘‹

Also! If you pass a non-numeric sequence as data for a numeric field, it gets formatted as a series of question marks. Very querulous of it. You can change that behaviour by giving the configuration option numeric a value that matches /\bSkipNaN\b/i β€” in which case any invalid numeric data is simply ignored. For example:

print form { numeric => 'SkipNaN' }
           '(]]]]].[[)',
           <<EONUMS;
           1
           two three
           4
EONUMS

would print:

(    1.0 )
(    4.0 )

🌸 Filling block fields with lists of values 🌸

If an argument corresponding to a field is an array reference, then form automatically joins the elements of that array into one single string, separating each element with a newline character. So a call like this:

@values = qw( 1 10 100 1000 );
print form "(]]]].[[)", \@values;

will print out

 (   1.00)
 (  10.00)
 ( 100.00)
 (1000.00)

as you'd expect. Good. Correct. Iconic πŸ’…

But β€” and this is the part people mess up β€” arrays must be passed by reference, so that form knows the entire array holds data for a single field. If that previous example had not passed @values by reference:

@values = qw( 1 10 100 1000 );
print form "(]]]].[[)", @values;

the output would have been:

 (   1.00)
 10
 100
 1000

Why? Because @values would've been interpolated into form's argument list, so only $value[0] gets used as the data for the initial format string. The remaining elements of @value get treated as separate format strings and printed out "verbatim". Not the vibe you wanted, ngl.

And also note: because arrays must be passed using a reference, their original contents get consumed by form β€” exactly like the contents of scalars passed by reference. Same energy.

To avoid having an array consumed by form, pass it as an anonymous array:

print form "(]]]].[[)", [@values];

πŸŽ€ Headers, footers, and pages πŸŽ€

The form subroutine can also insert headers, footers, and page-feeds while it formats. These features are controlled by the header, footer, pagefeed, pagelen, and pagenum options. Here's the rundown:

  • pagenum β€” takes a scalar value, or a reference to a scalar variable, and starts page numbering at that value. If you give it a reference to a scalar variable, that variable gets updated as formatting proceeds, so the final page number is sitting there in it after formatting is done. Super handy for multi-part reports.
  • pagelen β€” specifies the total number of lines in a page (including headers, footers, and page-feeds).
  • pagewidth β€” specifies the total number of columns in a page.

If header is given a string value, that string is used as the header of every page generated. If you give it a reference to a subroutine instead, that subroutine is called at the start of every page, and its return value is used as the header string. When it's called, the subroutine gets passed the current page number.

Likewise, if footer is given a string value, that string is used as the footer of every page generated. And if it's a reference to a subroutine, that subroutine is called at the start of every page, and its return value is used as the footer string. When it's called, the footer subroutine gets passed the current page number.

Both the header and footer options can also be given as hash references πŸ‘‘ In that case the hash entries for the keys left, centre (or center), and right specify what appears on the left, centre, and right of the header/footer. The entry for the key width specifies how wide the footer is to be. If the width key is omitted, the pagewidth configuration option is used β€” and that defaults to 72 characters.

The left, centre, and right values may be literal strings, or subroutines (just like a normal header/footer specification may be). Check the second example below for that.

Another alternative for the header and footer options: give them a subroutine that returns a hash reference. The subroutine is called for each page, and then the resulting hash is treated exactly like the hashes described in the paragraph above. Third example below, bestie.

The pagefeed option acts in exactly the same way, producing a pagefeed that gets appended after the footer. But note: the pagefeed is not counted as part of the page length.

All three of these page components are recomputed at the start of each new page, before the page contents are formatted. (Recomputing the header and footer first makes it possible to figure out how many lines of data to format, so you can adhere to the specified page length. Clever, right?)

When the call to form is complete and the data has been fully formatted, the footer subroutine is called one last time β€” with an extra argument of 1. The string returned by that final call is used as the final footer.

So for example, a 60-line-per-page report starting at page 7, with appropriate headers and footers, might be set up like so:

$page = 7;

form { header => sub { "Page $_[0]\n\n" },
       footer => sub { my ($pagenum, $lastpage) = @_;
                       return "" if $lastpage;
                       return "-"x50 . "\n"
                                     .form ">"x50, "...".($pagenum+1);
                      },
       pagefeed => "\n\n",
       pagelen  => 60
       pagenum => \$page,
     },
     $template,
     @data;

Not me pointing out the recursive use of form inside the footer option β€” because yes, that's happening 😭

Alternatively, to set up headers and footers so that the running head is right-justified in the header and the page number is centred in the footer:

form { header => { right => "Running head" },
       footer => { centre => sub { "Page $_[0]" } },
       pagelen  => 60
     },
     $template,
     @data;

That footer from the previous example could also have been specified the other way around β€” as a subroutine that returns a hash, rather than a hash containing a subroutine:

form { header => { right => "Running head" },
       footer => sub { return {centre => "Page $_[0]"} },
       pagelen  => 60
     },
     $template,
     @data;

πŸ¦‹ The cols option πŸ¦‹

Sometimes the data you need for a form call has to be extracted from a nested data structure. Like, if you already have your data in columns, printing a table is easy peasy:

@name  = qw(Tom Dick Harry);
@score = qw( 88   54    99);
@time  = qw( 15   13    18);

print form
'-------------------------------',
'Name             Score     Time',
'-------------------------------',
'[[[[[[[[[[[[[[   |||||     ||||',
 \@name,          \@score,  \@time;

But if the data is aggregated by rows:

@data = (
    { name=>'Tom',   score=>88, time=>15 },
    { name=>'Dick',  score=>54, time=>13 },
    { name=>'Harry', score=>99, time=>18 },
);

then you need to do some fancy mapping before it can be fed to form:

Okay so, the manual way to pull columns out of hashes looks like this:

print form
'-------------------------------',
'Name             Score     Time',
'-------------------------------',
'[[[[[[[[[[[[[[   |||||     ||||',
[map $$_{name},  @data],
[map $$_{score}, @data],
[map $$_{time} , @data];

Or you could just use the cols option, bestie:

use Text::Reform qw(form columns);

print form
'-------------------------------',
'Name             Score     Time',
'-------------------------------',
'[[[[[[[[[[[[[[   |||||     ||||',
{ cols => [qw(name score time)],
  from => \@data
};

This option takes an array of strings that specifies the keys of the hash entries to be extracted into columns. The from entry (which must be present) also takes an array, which is expected to contain a list of references to hashes. For each key specified, this option inserts into "form"'s argument list a reference to an array containing the entries for that key, extracted from each of the hash references supplied by from. So, for example, the option:

{ cols => [qw(name score time)],
  from => \@data
}

is replaced by three array references: the first containing the 'name' entries for each hash inside @data, the second containing the 'score' entries for each hash inside @data, and the third containing the 'time' entries for each hash inside @data.

If, instead, you have a list of arrays containing the data:

@data = (
        # Time  Name     Score
        [ 15,   'Tom',   88 ],
        [ 13,   'Dick',  54 ],
        [ 18,   'Harry', 99 ],
);

the cols option can extract the appropriate columns for that too. You just specify the required indices, rather than keys:

print form
'-----------------------------',
'Name             Score   Time',
'-----------------------------',
'[[[[[[[[[[[[[[   |||||   ||||',
{ cols => [1,2,0],
  from => \@data
}

Note that the indices can be in any order, and the resulting arrays are returned in the same order. Slay. ✨

If you need to merge columns extracted from two hierarchical data structures, just concatenate the data structures first, like so:

print form
'---------------------------------------',
'Name             Score   Time   Ranking
'---------------------------------------',
'[[[[[[[[[[[[[[   |||||   ||||   |||||||',
{ cols => [1,2,0],
  from => [@data, @olddata],
}

Of course, this only works if the columns are in the same positions in both data sets (and both datasets are stored in arrays) or if the columns have the same keys (and both datasets are in hashes). If not, you would need to format each dataset separately, like so:

print form
'-----------------------------',
'Name             Score   Time'
'-----------------------------',
'[[[[[[[[[[[[[[   |||||   ||||',
{ cols=>[1,2,0],  from=>\@data },
'[[[[[[[[[[[[[[   |||||   ||||',
{ cols=>[3,8,1],  from=>\@olddata },
'[[[[[[[[[[[[[[   |||||   ||||',
{ cols=>[qw(name score time)],  from=>\@otherdata };

🏷️ The tag sub

The tag subroutine may be exported from the module. It takes two arguments: a tag specifier and a text to be entagged. The tag specifier indicates the indenting of the tag, and of the text. The sub generates an end-tag (using the usual "/tag" variant), unless an explicit end-tag is provided as the third argument.

The tag specifier consists of the following components (in order):

  • An optional vertical spacer (zero or more whitespace-separated newlines)
    • One or more whitespace characters up to a final mandatory newline.
    • This vertical space is inserted before the tag and after the end-tag.
  • An optional tag indent
    • Zero or more whitespace characters. Both the tag and the end-tag are indented by this whitespace.
  • An optional left (opening) tag delimiter
    • Zero or more non-"word" characters (not alphanumeric or '_'). If the opening delimiter is omitted, the character '<' is used.
  • A tag
    • One or more "word" characters (alphanumeric or '_').
  • Optional tag arguments
    • Any number of any characters.
  • An optional right (closing) tag delimiter
    • Zero or more non-"word" characters which balance some sequential portion of the opening tag delimiter. For example, if the opening delimiter is "<-(" then any of the following are acceptable closing delimiters: ")->", "->", or ">". If the closing delimiter is omitted, the "inverse" of the opening delimiter is used (for example, ")->").
  • An optional vertical spacer (zero or more newlines)
    • One or more whitespace characters up to a mandatory newline. This vertical space is inserted before and after the complete text.
  • An optional text indent
    • Zero or more space or tab characters. Each line of text is indented by this whitespace (in addition to the tag indent).

For example:

$text = "three lines\nof tagged\ntext";

print tag "A HREF=#nextsection", $text;

prints:

<A HREF=#nextsection>three lines
of tagged
text</A>

whereas:

print tag "[-:GRIN>>>\n", $text;

prints:

[-:GRIN>>>:-]
three lines
of tagged
text
[-:/GRIN>>>:-]

and:

print tag "\n\n   <BOLD>\n\n   ", $text, "<END BOLD>";

prints:

   <BOLD>

      three lines
      of tagged
      text

   <END BOLD>

(with the indicated spacing fore and aft). Vibe check: passed. πŸ’…


πŸ‘‘ AUTHOR

Damian Conway (damian@conway.org)

πŸ› BUGS

The module uses POSIX::strtod, which may be broken under certain versions of Windows. Applying the WINDOWS_PATCH patch to Reform.pm will replace the POSIX function with a copycat subroutine.

There are undoubtedly serious bugs lurking somewhere in code this funky :-) Bug reports and other feedback are most welcome. No cap, feedback is love. 🫢

Copyright (c) 1997-2007, Damian Conway "<DCONWAY@CPAN.org>". All rights reserved.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic.

⚠️ DISCLAIMER OF WARRANTY

Okay, legal voice on: because this software is licensed free of charge, there is no warranty for the software, to the extent permitted by applicable law. Except when otherwise stated in writing, the copyright holders and/or other parties provide the software "AS IS" without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of MERCHANTABILITY and FITNESS FOR A PARTICULAR PURPOSE. The entire risk as to the quality and performance of the software is with you. Should the software prove defective, you assume the cost of all necessary servicing, repair, or correction.

And in no event, unless required by applicable law or agreed to in writing, will any copyright holder, or any other party who may modify and/or redistribute the software as permitted by the above licence, be liable to you for damages, including any general, special, incidental, or consequential damages arising out of the use or inability to use the software (including but not limited to loss of data or data being rendered inaccurate or losses sustained by you or third parties or a failure of the software to operate with any other software), even if such holder or other party has been advised of the possibility of such damages. Read it and weep, but like, legally. 😭


πŸ’– This lil' page is from Text::Reform(3pm), Perl v5.42.0, dated 2011-11-18. Byeee bestie, go format something iconic! πŸ’…βœ¨

πŸ“¦ where this page comes from