In a scripting language, you often run scripts from a command line and print things to STDOUT. For long output you can redirect it to a file via shell-redirection (
$ foo.rb > foo.txt).
But if you're using Clojure for ad-hoc scripting, you're probably sitting in a REPL, not running from a command line. REPLs generally don't have shell-redirection. Printed output just gets dumped into your REPL. This can be annoying. (After a good 10,000 lines of output into a REPL buffer, Emacs starts to lag.)
But you can write a macro to handle this easily enough.
(use 'clojure.contrib.duck-streams) (defmacro redir [filename & body] `(spit ~filename (with-out-str ~@body)))
user> (redir "foo.txt" (foo) (bar) (baz))
(foo) and friends would've printed to STDOUT will instead go to
foo.txt. I've found this somewhat useful at work lately.
Edit: better version via Graham Fawcett:
(defmacro redir [filename & body] `(binding [*out* (writer ~filename)] ~@body))