一种简单的解析程序参数的方法 [英] A simple way of parsing a program arguments

查看:98
本文介绍了一种简单的解析程序参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了一些关于解析程序参数的方法。他们似乎太复杂了。我需要一个简单的解决方案。但我也希望能够(最好不一定)按名称来引用参数。因此,如果像这样的命令:

I've seen some approaches about parsing program arguments. They seem to be too complicated. I need a simple solution. But I also want to be able (preferably, not necessarily) to refer to the arguments by name. So if a command like looks like this:

./MyApp --arg1Name arg1Value --arg2Name arg2Value

然后我想把它们当作 args [arg1Name] args [arg2Name] 来获取它们的值。但我知道这不是一个有效的Haskell代码。我现在拥有的并不多:

then I'd like to treat them as args["arg1Name"] and args["arg2Name"] to get their values. I know that's not a valid Haskell code, though. What I have now is not much:

main = do
  [args] <- getArgs

我再说一遍,我想要一个简单的解决方案,最好不涉及任何第三方haskell库。

I repeat, I'd like a simple solution, preferably without involving any third-party haskell libraries.

推荐答案

如何将它们成对解析并添加到地图中:

How about just parsing them in pairs and adding them to a map:

simpleArgsMap :: [String] -> Map String String
simpleArgsMap [] = Map.empty
simpleArgsMap (('-':'-':name):value:rest)
    = Map.insert name value (simpleArgsMap rest)
simpleArgsMap xs = error $ "Couldn't parse arguments: " ++ show xs

一个简单的包装程序来显示这个工作:

A simple wrapper program to show this working:

module Args where

import System.Environment ( getArgs )
import Control.Applicative ( (<$>) )

import qualified Data.Map as Map
import Data.Map ( Map )

main = do
  argsMap <- simpleArgsMap <$> getArgs
  print $ Map.lookup "foo" argsMap

这篇关于一种简单的解析程序参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆