如何使用 ghci 加载没有 .hs 扩展名的 runhaskell 脚本?

发布于 2024-12-16 20:16:04 字数 783 浏览 5 评论 0原文

我在 haskell 中编写了一个名为 testscript 的脚本,代码如下:

#!/usr/bin/env runhaskell

main = putStrLn "hello"

使脚本可执行后,我可以使用 ./testscript 运行它。但是,当我尝试使用 ghci(即使用 :l testscript)加载脚本时,

target `testscript' is not a module name or a source file

如果我将 testscript 重命名为 testscript.hs,并尝试再次使用 ghci 加载,我收到错误

testscript.hs:1:0:  error: invalid preprocessing directive #!
phase `C pre-processor' failed (exitcode = 1)

如果我删除 shebang 行,它可以正常工作。然而,必须向脚本添加 .hs 扩展名,删除顶行,然后删除 .hs 扩展名,并在每次需要时添加 shebang 行,这很乏味在 ghci 中尝试该脚本(每次我想对其进行更改时,这都很常见)。有没有更简单的方法来做到这一点?

我在 Mac OS X 10.6.8 下使用 ghc 版本 7.0.3

I have written a script in haskell named testscript with the following code:

#!/usr/bin/env runhaskell

main = putStrLn "hello"

After making the script executable, I can run it using ./testscript. However, when I try to load the script with ghci (ie with :l testscript), I get the error

target `testscript' is not a module name or a source file

If I rename testscript to testscript.hs, and try loading with ghci again, I get the error

testscript.hs:1:0:  error: invalid preprocessing directive #!
phase `C pre-processor' failed (exitcode = 1)

If I remove the shebang line it works fine. However it is tedious to have to add a .hs extension to the script, remove the top line, then remove the .hs extension and add the shebang line every time I want to try the script in ghci (which is pretty common everytime I want to make a change to it). Is there an easier way to do this?

I'm using ghc version 7.0.3 under Mac OS X 10.6.8

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪痕残 2024-12-23 20:16:04

您可以使用 -x 选项告诉 GHCi(或 GHC)将所有后续文件视为具有指定的扩展名。

似乎没有任何方法可以从 GHCi 中指定此选项(与 :load 一起使用),但如果您希望这样做,可以使用一个解决方法,即使用 创建符号链接>.hs 扩展名并加载它。

shebang 行的第二个问题是由于某种原因在源文件上运行 C 预处理器引起的(我在 Ubuntu 上安装的旧 GHC 不会执行此操作)。您可以使用 -XNoCPP 选项禁用此功能。

因此,对于您的情况,这应该可以从命令行运行:

ghci -x hs -XNoCPP testscript

You can use the -x option to tell GHCi (or GHC for that matter) to treat all following files as if they had the specified extension.

There doesn't seem to be any way to specify this option from within GHCi (for use with :load), but a workaround you can use if you want this is to create a symlink with a .hs extension and load that.

Your second problem with the shebang line is caused by the C preprocessor being run on your source file for some reason (my old GHC install on Ubuntu does not do this). You can disable this by using the -XNoCPP option.

So for your case, this should work from the command line:

ghci -x hs -XNoCPP testscript
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文