This post originated from an RSS feed registered with Scala Buzz
by Zemian Deng.
Original Post: Parsing simple command line options in Scala
Feed Title: thebugslayer
Feed URL: http://www.jroller.com/thebugslayer/feed/entries/atom?cat=%2FScala+Programming
Feed Description: Notes on Scala and Sweet web framework
I noticed there is an example from Scala site on using match to parse the command line options. I wondered if there is better way to do this without making the "verbose" variable mutable.
After looking around on the Scala API, I noticed the "partition" method in Iterable class could be useful in this case. Here is my attempt to parse some simple command line options apart from arguments inputs. I will assume all options can start with "-" or "--", and if there is optional-parameter, it must use "=" in between without space.
//file: test.scala
//seperate options from argumetns
val (opts, args) = argv.partition{ _.startsWith("-") }
//turning options array into map
val optsMap = Map() ++ opts.map{ x =>
val pair = x.split("-{1,2}")(1).split("=")
if(pair.length ==1) (pair(0), "true") else (pair(0), pair(1))
}
//use the option values
val verbose = optsMap.getOrElse("v", "false").toBoolean
val number = optsMap.getOrElse("n", "0").toInt
if(verbose)
println("program started")
println("number used in program is " + number)
println("program arguments count is " + args.length)
Testing:
oolarcher07:scala thebugslayer$ scala test.scala
number used in program is 0
program arguments count is 0
coolarcher07:scala thebugslayer$ scala test.scala -v
program started
number used in program is 0
program arguments count is 0
coolarcher07:scala thebugslayer$ scala test.scala -v 1 2 3
program started
number used in program is 0
program arguments count is 3
coolarcher07:scala thebugslayer$ scala test.scala -v 1 2 3 -n=55
program started
number used in program is 55
program arguments count is 3
coolarcher07:scala thebugslayer$ scala test.scala -v 1 2 3 --n=55
program started
number used in program is 55
program arguments count is 3
If you know any other interesting ways, please share.