proposed extension to format/printf : POSIX-style numbered placeholders

27 views
Skip to first unread message

John-Philip Butler

unread,
Jul 22, 2025, 9:41:36 AM7/22/25
to forum
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


Henry Rich

unread,
Jul 22, 2025, 10:12:34 AM7/22/25
to fo...@jsoftware.com
I wrote printf and do not plan any improvements.  If you want to add to it, go ahead.

Henry Rich
To unsubscribe from this group and stop receiving emails from it, send an email to forum+un...@jsoftware.com.

John-Philip Butler

unread,
Jul 23, 2025, 3:47:50 AM7/23/25
to forum, Henry Rich
ok, i will give it a try! but it might take a while to muster enough time to do it
Reply all
Reply to author
Forward
0 new messages