代码之家  ›  专栏  ›  技术社区  ›  justinhj

运行ghci时,如何将stdin从文件路由到函数

  •  6
  • justinhj  · 技术社区  · 15 年前

    我在XP的DOS命令行中使用ghci 6.10.4,在使用haskell-mode-2.4的emacs中也使用ghci 6.10.4。

    当运行在stdin上运行的程序时,有没有方法可以将文件重定向为stdin?例如,如果我有一个名为main的函数,它从stdin中读取,我就不能这样做:

    *Main> main < words.txt
    

    还有别的办法吗?

    另外,我希望能够在ghci窗口中输入stdin,这似乎有效,但eof键是什么?我以为是ctrl-d,但不管用。

    2 回复  |  直到 15 年前
        1
  •  6
  •   ephemient    15 年前

    如果你重做你的 main 打开文件本身。

    import System.Environment
    import System.IO
    
    main :: IO ()
    main = do
        args <- getArgs
        case args of
          [] -> doStuff stdin
          file:_ ->
            withFile file ReadMode doStuff
    
    doStuff :: Handle -> IO ()
    doStuff = …
    
    *Main> System.Environment.withArgs ["main.txt"] main
    

    在GHCI内,不要在stdin上给出EOF。如果这样做,所有进一步的读取stdin的尝试都将失败:

    Prelude> getLine
    *** Exception: <stdin>: hGetLine: illegal operation (handle is closed)
    Prelude> getContents
    *** Exception: <stdin>: hGetContents: illegal operation (handle is closed)
    
        2
  •  4
  •   codebliss    15 年前

    您可以在ghci中键入:main来调用命令行参数。恐怕你只是想用一下。