I may be in the minority here, but I very much enjoy Perl's formats. I especially like being able to wrap a long piece of text within a column ("~~ ^<<<<<<<<<<<<<<<<" type stuff). Are there any other programming languages that have similar features, or libraries that implement similar features? I am especially interested in any libraries that implement something similar for Ruby, but I'm also curious about any other options.
views:
252answers:
3
+2
A:
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"
dsm
2008-10-25 16:30:02
+6
A:
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
Robert Gamble
2008-10-25 16:30:46
+11
A:
I seem to recall something similar in Fortran when I used it many years ago (however it may well have have been 3rd 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 config & pkg vars 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;
/I3az/
draegtun
2008-10-25 21:23:19