如何从 clojure 中的 stdin (*in*) 读取行 [英] How to read lines from stdin (*in*) in clojure

查看:19
本文介绍了如何从 clojure 中的 stdin (*in*) 读取行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写我的第一个 clojure 程序,并想从 stdin 中读取行.

I am writing my first clojure program, and want to read lines from stdin.

当我尝试这个时:

(doall (map #(println %) (line-seq *in*)))

我收到此异常:

Exception in thread "main" java.lang.ClassCastException: clojure.lang.LineNumberingPushbackReader cannot be cast to java.io.BufferedReader (test.clj:0)

我在 1.0 和 1.1 版本中得到相同的结果

I get the same results in version 1.0 and 1.1

那么如何将 *in* 转换为可以迭代的序列?我本以为这很常见,以至于 *in* 本身是可迭代的,但这也不起作用 - 如果我尝试直接使用它,我会得到:

So how do I convert *in* into a seq I can iterate over? I would have thought that this is common enough that *in* itself would be iterable, but that does not work either - if I try to use it directly I get:

java.lang.IllegalArgumentException: Don't know how to create ISeq from: clojure.lang.LineNumberingPushbackReader (NO_SOURCE_FILE:0)

另外,有没有在 clojure 中做一般文件处理的例子?

Also, are there any examples of doing general file handling in clojure?

推荐答案

尝试包装 *in*java.io.BufferedReader 中.并且还使用 doseq 而不是 doall,正如 devstopfix 指出的:

Try wrapping *in* in a java.io.BufferedReader. And also use doseq instead of doall, as devstopfix pointed out:

(doseq [ln (line-seq (java.io.BufferedReader. *in*))]
   (println ln))

注意line-seq 被记录为需要 BufferedReader 作为其来源.

Note that line-seq is documented to require a BufferedReader as its source.

这篇关于如何从 clojure 中的 stdin (*in*) 读取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆