Skip to content

Instantly share code, notes, and snippets.

@tototoshi
Created January 5, 2012 13:31
Show Gist options
  • Save tototoshi/1565265 to your computer and use it in GitHub Desktop.
Save tototoshi/1565265 to your computer and use it in GitHub Desktop.
Scalaでスクリプトとか書くときのコマンドライン引数の解析
#!/bin/sh
exec scala "$0" "$@"
!#
val helpMessage = """
Usage:
-n do not output the trailing newline
-x repeat x times
--help display this help and exit
"""
// オプションを表すcase class
case class Args(newLine: Boolean, repeat: Int, help: Boolean, message: String)
def parseArgs(args: List[String]): Option[Args] = {
// デフォルト値
var newLine = true
var repeat = 1
var help = false
// こんな感じで再帰関数作る
@scala.annotation.tailrec
def parseArgsHelper(args: List[String]): Args = {
args match {
case "-n" :: rest => {
newLine = false
parseArgsHelper(rest)
}
case "-x" :: x :: rest => {
repeat = x.toInt
parseArgsHelper(rest)
}
case "--help" :: rest => Args(newLine, repeat, true, "")
case message => Args(newLine, repeat, false, message.mkString(" "))
}
}
try { Some(parseArgsHelper(args)) } catch { case _ => None }
}
def doEcho(args: Args): Unit = args match {
case Args(_, _, true, _) => println(helpMessage)
case Args(true, repeat, _, message) => (1 to repeat) foreach { _ => println(message) }
case Args(false, repeat, _, message) => (1 to repeat) foreach { _ => print(message) }
}
def main = parseArgs(args.toList) match {
case Some(args) => doEcho(args)
case None => println("Invalid Arguments ヽ(`Д´)ノ!!")
}
main
/*
$ ./echo.scala -x a
Invalid Arguments ヽ(`Д´)ノ!!
$ ./echo.scala -x 3 foo
foo
foo
foo
$ ./echo.scala -n -x 3 foo
foofoofoo%
$ ./echo.scala -n -x 3 foo bar baz
foo bar bazfoo bar bazfoo bar baz%
$ ./echo.scala -x 3 foo bar baz
foo bar baz
foo bar baz
foo bar baz
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment