chicken-scheme - 如何读取通过标准输入传入的所有行?

chicken-scheme - how does one read all the lines passed in via standard input?

我正在尝试读取通过标准输入传递给小鸡方案脚本的所有行,并将它们放入列表中,但我似乎无法正确确定何时我'已经到达输入的末尾。另一个测试脚本似乎表明测试 (eof-object? results-of-last-read-line-call) 是一个合法的测试,但在下面的例子中它只是坐在那里无限阅读。

我整理了以下测试脚本。我用 cat some_file.txt | this_script.scm

来调用它
#! /usr/local/bin/csi -script

(define (read-from-stdin collection line)
  (if (eof-object? line) ; bad test? 
    collection
     (read-from-stdin (cons collection line) read-line)
  ) ; yes, i know atypical formatting. Done so you can see they're all there
)

(for-each print (read-from-stdin '() (read-line)))

问题是您在递归调用中传递了 过程 read-line。这会导致测试总是失败(因为过程永远不会是 eof-object)。相反,您可能想要 调用 read-line 并传递行字符串:

(define (read-from-stdin collection line)
  (if (eof-object? line) ; the test is fine
      collection
      (read-from-stdin (cons collection line) (read-line))))

(for-each print (read-from-stdin  '() (read-line)))

您还调用了 cons 并且参数颠倒了,所以我也解决了这个问题。也许这是在反向添加线条的尝试?相反,你可能想在最后反转这些行,所以你会得到

(for-each print (reverse (read-from-stdin  '() (read-line))))

或者您当然可以在 read-from-stdin 中调用 (reverse collection)

我喜欢为此使用 read-lines。 这是您使用它编写的程序:

#!/usr/local/bin/csi -script
(for-each print (read-lines))

已测试并有效。 对于 csc,将 #! 行替换为 (use extras).