Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing the "original" return value from with-out-str

Tags:

clojure

I'm using with-out-str to capture some data that is printed to stdout. Problem is that with-out-str seems to throw away the return value from my function. Is there any way I can capture both? I'd like to have my cake and eat it too.

Example:

(with-out-str (do (prn "test") (+ 1 1)))
like image 697
erikcw Avatar asked Aug 22 '11 16:08

erikcw


1 Answers

Aping the definition of the core library's with-out-str macro, you could define a similar one like this:

(defmacro with-out-str-and-value
  [& body]
  `(let [s# (new java.io.StringWriter)]
     (binding [*out* s#]
       (let [v# ~@body]
         (vector (str s#)
                 v#)))))

Without the values function from Common Lisp and its multiple function return values, here we return a vector instead; the first item is the text collected from standard output, and the second item is the value returned by evaluating the body form.

like image 60
seh Avatar answered Sep 29 '22 00:09

seh