从 stdin 获取路径并将其用作 readFile 的参数

Taking a path from stdin and using it as argument to readFile

作为学习策略,我尝试修改Prelude interact功能。

test.hs 内容

interact' :: (String -> String) -> IO ()
interact' f = do
  path <- getContents
  s <- readFile path
  putStr (f s)

main :: IO ()
main = interact' id

test.txt 内容

Hello World

调用echo "test.txt" | runhaskell test.hs不显示Hello World。我是不是忽略了什么?

echo "test.txt" 生成字符串 test.txt\n,并且您没有名为 test.txt\n 的文件,只有一个名为 test.txt 的文件。在 Haskell 中使用 getLine 而不是 getContents 来不获取换行符,或者在 shell 中使用 printf 而不是 echo 来不发出首先换行。