What other languages have features and/or libraries similar to Perl's format?
I seem to recall something similar in Fortran when I used it many years ago (however, it may well have have been a third-party library).
As for other options in Perl, have a look at Perl6::Form
.
The form
function replaces format
in Perl6. Damian Conway in "Perl Best Practices" recommends using Perl6::Form
with Perl5 citing the following issues with format
....
- statically defined
- rely on global variables for configuration and pkg variables for data they format on
- uses named filehandles (only)
- not recursive or re-entrant
Here is a Perl6::Form
variation on the Ruby example by Robert Gamble....
use Perl6::Form;
my ( $month, $day, $year ) = qw'Sep 18 2001';
my ( $num, $numb, $location, $toe_size );
for ( "Market", "Home", "Eating Roast Beef", "Having None", "On the way home" ) {
push @$numb, ++$num;
push @$location, $_;
push @$toe_size, $num * 3.5;
}
print form
' Piggy Locations for {>>>}{>>}, {<<<<}',
$month, $day, $year ,
"",
' Number: location toe size',
' --------------------------------------',
'{]}) {[[[[[[[[[[[[[[[} {].0} ',
$numb, $location, $toe_size;
FormatR provides Perl-like formats for Ruby.
Here is an example from the documentation:
require "formatr"
include FormatR
top_ex = <<DOT
Piggy Locations for @<< @#, @###
month, day, year
Number: location toe size
-------------------------------------------
DOT
ex = <<TOD
@) @<<<<<<<<<<<<<<<< @#.##
num, location, toe_size
TOD
body_fmt = Format.new (top_ex, ex)
body_fmt.setPageLength(10)
num = 1
month = "Sep"
day = 18
year = 2001
["Market", "Home", "Eating Roast Beef", "Having None", "On the way home"].each {|location|
toe_size = (num * 3.5)
body_fmt.printFormat(binding)
num += 1
}
Which produces:
Piggy Locations for Sep 18, 2001
Number: location toe size
-------------------------------------------
1) Market 3.50
2) Home 7.00
3) Eating Roast Beef 10.50
4) Having None 14.00
5) On the way home 17.50
There is the Lisp (format ...)
function. It supports looping, conditionals, and a whole bunch of other fun stuff.
for example (copied from above link):
(defparameter *english-list*
"~{~#[~;~a~;~a and ~a~:;~@{~a~#[~;, and ~:;, ~]~}~]~}")
(format nil *english-list* '()) ;' ==> ""
(format nil *english-list* '(1)) ;' ==> "1"
(format nil *english-list* '(1 2)) ;' ==> "1 and 2"
(format nil *english-list* '(1 2 3)) ;' ==> "1, 2, and 3"
(format nil *english-list* '(1 2 3 4));' ==> "1, 2, 3, and 4"