Version française
Home     About     Download     Resources     Contact us    
Browse thread
Run-time evaluation of a Printf format string
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jan Kybic <kybic@f...>
Subject: Re: [Caml-list] Run-time evaluation of a Printf format string
> Jan Kybic wrote:
>>         I would need an equivalent of Printf.sprintf where the 
>> format string is not constant, it is read from the command line.
>> The motivation is to let the user specify a template for file names,
>> such as "img%03d.png". Can this be achieved in Ocaml? It seems not, as 
>> Pervasives.string_of_format only accepts constant strings.
>> Or is there some external library useful for this task?
>

> Stéphane Glondu <steph@glondu.net> writes:
> What about Scanf.format_from_string?

> Dave Benjamin <dave@ramenlabs.com> writes:
> Does it have to be printf-style formatting? If you can switch to a
> syntax like $(foo), you can use Buffer.add_substitute:



Thank you for all your suggestions. Here is my summary:

- If I only want to insert a suitably formatted sequence number,
  the simplest solution is using Scanf.format_from_string, such as

  let format = "img%03d.png" in 
  Printf.sprintf (Scanf.format_from_string format "%d") num

- If I want to be able to insert several different variables
  (e.g. sequence number, image height and width) but do not
  have to specify formatting (like padding zeroes), then
  Buffer.add_substitute is easy enough to use.

- If I want both to insert several different variables and to 
  specify the formatting, I will have to implement my own parser and
  interpreter of format strings.

Jan



-- 
-------------------------------------------------------------------------
Jan Kybic <kybic@fel.cvut.cz>                       tel. +420 2 2435 5721
http://cmp.felk.cvut.cz/~kybic                      ICQ 200569450