3

I would like to read the entire string into a list, but not evaluate it. wtf? is the function or mix of functions which I can not find to do this.

user=> (wtf?  " S  I I ( S I I)")
(S I I (S I I))

The function should also work as:

user=> (last (wtf?  " S  I I ( S I I)"))
(S I I)

read-string returns only the first object, while load-string returns them all, but tries to evaluate them.

4

2 回答 2

2

这就是我使用的:

(defn safe-read
  "Evaluate the string in a safe way"
  [s]
  (binding [*read-eval* false]
    (read-string s)))

从文档:

“当设置为逻辑假时,在线程本地绑定的读取/加载中禁用 EvalReader (#=(...))。例如:

(binding [*read-eval* false] (read-string \"#=(eval (def x 3))\"))

所以它的作用是像往常一样读取字符串,但禁用评估。

因此,您可以使用此功能读取打印出来的地图、列表和矢量,而不必担心评估恶意代码。(好吧,我确定这在多大程度上是安全的,但对于日常使用来说,它可以完成这项工作)。

于 2012-09-02T17:12:29.403 回答
2

我就是个菜鸟。我很高兴了解安全阅读,但似乎我最初的问题是通过在表单周围添加 () 来解决的,这是我在尝试安全阅读时无意中所做的。

user=> (read-string  "( S  I I ( S I I))")
(S I I (S I I))

user=> (last (read-string  "( S  I I ( S I I))"))
(S I I)
于 2012-09-02T17:46:50.027 回答