加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 解析命令行参数的最佳方法?

发布时间:2020-12-16 09:26:32 所属栏目:安全 来源:网络整理
导读:在Scala中解析命令行参数的最佳方法是什么? 我个人更喜欢轻量级的东西,不需要外部罐子. 有关: Java library for parsing command-line parameters? What parameter parser libraries are there for C++? Best way to parse command line arguments in C#
在Scala中解析命令行参数的最佳方法是什么?
我个人更喜欢轻量级的东西,不需要外部罐子.

有关:

> Java library for parsing command-line parameters?
> What parameter parser libraries are there for C++?
> Best way to parse command line arguments in C#

解决方法

对于大多数情况,您不需要外部解析器. Scala的模式匹配允许以功能样式消费args.例如:

object MmlAlnApp {
  val usage = """
    Usage: mmlaln [--min-size num] [--max-size num] filename
  """
  def main(args: Array[String]) {
    if (args.length == 0) println(usage)
    val arglist = args.toList
    type OptionMap = Map[Symbol,Any]

    def nextOption(map : OptionMap,list: List[String]) : OptionMap = {
      def isSwitch(s : String) = (s(0) == '-')
      list match {
        case Nil => map
        case "--max-size" :: value :: tail =>
                               nextOption(map ++ Map('maxsize -> value.toInt),tail)
        case "--min-size" :: value :: tail =>
                               nextOption(map ++ Map('minsize -> value.toInt),tail)
        case string :: opt2 :: tail if isSwitch(opt2) => 
                               nextOption(map ++ Map('infile -> string),list.tail)
        case string :: Nil =>  nextOption(map ++ Map('infile -> string),list.tail)
        case option :: tail => println("Unknown option "+option) 
                               exit(1) 
      }
    }
    val options = nextOption(Map(),arglist)
    println(options)
  }
}

将打印,例如:

Map('infile -> test/data/paml-aln1.phy,'maxsize -> 4,'minsize -> 2)

这个版本只需要一个infile.易于改进(通过使用List).

另请注意,此方法允许连接多个命令行参数 – 甚至超过两个!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读