Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Haskell's getArgs from parsing glob expressions

I'm using getArgs in my Haskell program to parse arguments from the command line. However, I've noticed that I have problems when I call my program like this:

runhaskell Main *.hs .

As you can imagine, Main looks at *.hs files in the . directory.

But there's a problem. The code below doesn't behave as I'd expect.

import System

main :: IO ()
main = do
    args <- getArgs
    print args

I want to see

args = ["*.hs","."]

but instead I see

args = ["file1.hs","file2.hs","file3.hs","."]

My program needs to expand the glob expression itself because it does it in multiple directories. But how can I have getArgs return the raw list of arguments instead of trying to be magical and do the parsing itself?

like image 547
Elliot Cameron Avatar asked Nov 28 '22 18:11

Elliot Cameron


2 Answers

getArgs doesn't parse the glob expressison - getArgs never sees the glob expression. The glob expression is parsed and expanded by your shell before your program even starts.

There's nothing you can do inside your program to prevent this - your only option is to escape the glob in the shell (by adding a backslash before the * for example or surrounding the argument with single quotes).

like image 30
sepp2k Avatar answered Dec 04 '22 15:12

sepp2k


This isn't haskell, this is your shell.

Normally file globs (like *.hs) are interpreted by the shell before the command is passed to haskell.

To see this try running

 runhaskell Main '*.hs' .

The single quotes will prevent your shell from interpreting the glob, and pass the argument as-is to runhaskell.

like image 185
rampion Avatar answered Dec 04 '22 14:12

rampion