I have recently experimented with a small extension to sprintf, using numbered placeholders in POSIX-like syntax (eg: %2$s does a %s using argument in position 2). This turns out to be immensely useful when dealing with multiline text snippets as when generating text in another language (XML, Jd, R, ...). Simply using numbers works very well with J, there is no need for named parameters. The templates and code are easy to maintain as the format string can be reordered without changing the code; this also allows a form of polymorphism: the same code can generate text in a multitude of languages (eg. XML and sexp), even if they do not require exactly the same inputs. Maybe this is worth considering for integration with format/printf? Otherwise the regex based preprocessor below works for the cases i have encountered so far.
NB.*PHPat n Placeholder pattern for POSIX-style numbered placeholders
PHPat =: rxcomp'(^|[^%])%([[:digit:]]*)\$([^a-z]*[a-z])'
NB.*printfaux v Compile a numbered placeholder string into a list of arg numbers and a sprintf stri,g
printfaux =: 3 : 0
TS=.y NB. template string
M =.PHPat rxmatches TS NB. Matches
MS =. M rxfrom TS NB. match strings
if. 0 < # M do.
Id=.(0&".)&> 2 {"1 MS
Format =. ;&.> <"1 (1{"1 MS) ,. (<'%') ,.3 {"1 MS
Segs =. ( {."2 M) rxcut TS
PrintfStr =. ; Format (>: +: i. # Format) } Segs
Id ; PrintfStr
else.
(0$0) ; TS
end.
)
NB.*esprintf d Extended sprintf: perform sprintf substitution with argument selection
NB.-example:
NB.- (prinfaux PosixLikeTemplate) esprintf Args
esprintf =: (1 {:: [) sprintf ] {"1 ~ 0 {:: [
NB. ------- sample usage
HtmlHeader =: printfaux 0 : 0
<!DOCTYPE html>
<html>
<head><title>%0$s %2$s</title></head>
<body>
<h1>
<title>%0$s</title>
</h1>
)
myVerb=: 3 : 0
...
Out =. HtmlHeader esprintf Title ; Author ;Timestamp