【问题标题】:Haskell how to read a file specified as a command line argumentHaskell如何读取指定为命令行参数的文件
【发布时间】:2012-04-16 21:59:16
【问题描述】:

我需要编写一个从命令行参数检索文件并逐行读取该文件的 haskell 程序。我想知道如何解决这个问题,我是否必须将命令行参数作为字符串并将其解析为 openFile 或其他内容?我对 haskell 很陌生,所以我很迷茫,任何帮助将不胜感激!

【问题讨论】:

    标签: haskell stdin readfile


    【解决方案1】:

    首先,使用getArgs 获取命令行参数。我想第一个对你来说是最有趣的。然后,使用openFile 函数打开文件。最后,使用hGetLine逐行读取打开的文件。

    【讨论】:

      【解决方案2】:

      是的,如果想要指定一个文件作为参数,那么必须获取参数并将其发送到 openFile。

      System.Environment.getArgs 将参数作为列表返回。所以给test_getArgs.hs点赞

      import System.Environment (getArgs)
      
      main = do
              args <- getArgs
              print args
      

      那么,

      $ ghc test_getArgs.hs -o test_getArgs
      $ ./test_getArgs
      []
      $ ./test_getArgs arg1 arg2 "arg with space"
      ["arg1","arg2","arg with space"]
      

      所以,如果你想读取单个文件:

      import System.Environment (getArgs)
      import System.IO (openFile, ReadMode, hGetContents)
      
      main = do
              args <- getArgs
              file <- openFile (head args) ReadMode
              text <- hGetContents file
              -- do stuff with `text`
      

      (注意该代码没有错误恢复:如果没有参数并且args 为空(head 将失败)怎么办?如果文件不存在/不可读怎么办?)

      【讨论】:

      • 什么是对 IO 字符串的数字求和的好方法?
      • @SNpn,求和哪些数字? (您必须提供更多信息)
      • 对不起,该文件包含一个整数列表(每行设置一个整数)我需要检索文件并对整数求和,我试过print . sum (text)
      • 您可能会发现mapreadlines 很有用(这些都是文档的链接)。 (另外,该代码应该是print . sum $ text,因为. 只组成函数,而您编写的内容被解析为print . (sum text)
      • 如果您使用模式匹配,您可以完全避免 head 调用:(firstArg:_) &lt;- getArgs。另外,考虑使用withFile 来确保文件被关闭。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      • 2011-08-30
      • 1970-01-01
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多