Skip to content

Instantly share code, notes, and snippets.

@takezoux2
Created January 31, 2012 03:04
Show Gist options
  • Save takezoux2/1708461 to your computer and use it in GitHub Desktop.
Save takezoux2/1708461 to your computer and use it in GitHub Desktop.
Simple command line args parser.
/*
{{{
def main(args : Array[String]) = {
val aMap = SimpleArgsParser.parse(args)
...
}
}}}
Parse command line args and convert to Map
For example
"scala hoge.scala -f fuga.txt --help -v"
Args is Array("-f","fuga.txt","--help","-v").
And it is converted to Map("f" -> "fuga.txt","help" -> "","v" -> "").
*/
object SimpleArgsParser{
def parse(args : Array[String]) : Map[String, String] = {
if(args.length == 0) return Map.empty
var map = Map[String, String]()
def toKey( v : String) = {
if(v.startsWith("--")){
v.substring(2)
}else{
v.substring(1)
}
}
args.sliding(2,1).foreach( l => {
if(l(0).startsWith("-")){
val key = toKey(l(0))
if(l(1).startsWith("-")){
map +=( key -> "")
}else{
map +=(key -> l(1))
}
}
})
if(args(args.length - 1).startsWith("-")){
val key = toKey(args(args.length - 1))
map +=(key -> "")
}
map
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment