Hey, I wrote my first functional program in Scala. It works like grep with very limited features. It only allows -n and -v options.
Scala definitely offers some unique features that can take many moons to master.
- /*
 - // Simple grep program written in Scala
 - //
 - // CJKim, 4-Sep-2015, first version
 - //
 - // vim: set sw=2 ts=2
 - */
 - import scala.io.Source
 - import java.io.{FileReader, FileNotFoundException, IOException}
 - import scala.util.matching.Regex
 - object grep {
 - var o_invert = false
 - var o_plinen = false
 - def usage() {
 - println("""
 - usage: scala Filter [options] regex filename [[filename]...]
 - options:
 - -h or -help : print this message
 - -v or -invert : invert the sense of matching
 - -V or -version : print version info
 - """)
 - System.exit(1)
 - }
 - def main(args: Array[String]) {
 - var shift = 0
 - for (a <- args if a.startsWith("-")) {
 - a match {
 - case "-h" | "-help" =>
 - usage()
 - case "-n" | "-line" =>
 - o_plinen = true;
 - case "-v" | "-invert" =>
 - o_invert = true
 - case "-V" | "-version" =>
 - println("Scala grep version 0.01 - CJKim")
 - System.exit(0)
 - case z =>
 - println("Unknown option: '" + z + "'")
 - }
 - shift += 1
 - }
 - if (args.length - shift < 2)
 - usage()
 - val pattern = new Regex(args(shift))
 - val files = args.drop(shift + 1)
 - for (f <- files) {
 - var linenum = 0
 - try {
 - for (line <- Source.fromFile(f).getLines()) {
 - linenum += 1
 - var mat = pattern findFirstIn line
 - if (mat == None) {
 - if (o_invert) {
 - if (o_plinen) printf("%d: ", linenum)
 - println(line)
 - }
 - }
 - else {
 - if (!o_invert) {
 - if (o_plinen) printf("%d: ", linenum)
 - println(line)
 - }
 - }
 - }
 - } catch {
 - case e: FileNotFoundException => printf("File %s not found\n", f)
 - case e: IOException => printf("Cannot read %s\n", f)
 - }
 - }
 - }
 - }
 
No comments:
Post a Comment