How to print a line to STDERR and STDOUT in OCaml?

In OCaml, how to print a string as a line to STDOUT? That is, the string and the newline character, nicely?

And similarly, how to print the line to STDERR?

asked Jun 5 by dtivl (2,500 points)

1 Answer

In OCaml, you may print a string with the end line character to STDOUT using the function in the Pervasives module:

val print_endline : string -> unit

Print a string, followed by a newline character, on standard output and flush standard output.

One usage example:

$ ocaml
        OCaml version 4.01.1+dev2-2013-12-18+CLOSED

# print_endline "hello world!";;
hello world!
- : unit = ()
# 

In OCaml, you can use the Printf.eprintf function to print to STDERR (which is in Pervasives.stderr).

Examples:

Use Printf.eprintf:

$ rlwrap ocaml 2>/tmp/a.txt
        OCaml version 4.01.1+dev2-2013-12-18+CLOSED

Cannot find file topfind.
Unknown directive `thread'.
# Printf.eprintf "hello world!";;
- : unit = ()
# 
$ cat /tmp/a.txt
hello world!

Use Printf.fprintf to print to Pervasives.stderr:

$ rlwrap ocaml 2>/tmp/a.txt
        OCaml version 4.01.1+dev2-2013-12-18+CLOSED

Cannot find file topfind.
Unknown directive `thread'.
# Printf.fprintf Pervasives.stderr "hello world!";;
- : unit = ()
# 
$ cat /tmp/a.txt
hello world!
answered Jun 5 by dtivl (2,500 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...