Monday, May 9, 2016

grep in Scala

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.

  1. /* 
  2. // Simple grep program written in Scala 
  3. // 
  4. // CJKim, 4-Sep-2015, first version 
  5. // 
  6. // vim: set sw=2 ts=2 
  7. */  
  8.   
  9. import scala.io.Source  
  10. import java.io.{FileReader, FileNotFoundException, IOException}  
  11. import scala.util.matching.Regex  
  12.   
  13. object grep {  
  14.   var o_invert = false  
  15.   var o_plinen = false  
  16.   
  17.   def usage() {  
  18.     println("""  
  19. usage: scala Filter [options] regex filename [[filename]...]  
  20.   options:  
  21.     -h or -help    : print this message  
  22.     -v or -invert  : invert the sense of matching  
  23.     -V or -version : print version info  
  24. """)  
  25.     System.exit(1)  
  26.   }  
  27.   
  28.   def main(args: Array[String]) {  
  29.     var shift = 0  
  30.     for (a <- args if a.startsWith("-")) {  
  31.       a match {  
  32.         case "-h" | "-help"    =>  
  33.           usage()  
  34.         case "-n" | "-line"    =>  
  35.           o_plinen = true;  
  36.         case "-v" | "-invert"  =>  
  37.           o_invert = true  
  38.         case "-V" | "-version" =>  
  39.           println("Scala grep version 0.01 - CJKim")  
  40.           System.exit(0)  
  41.         case z                 =>  
  42.           println("Unknown option: '" + z + "'")  
  43.       }  
  44.       shift += 1  
  45.     }  
  46.     if (args.length - shift < 2)  
  47.       usage()  
  48.     val pattern = new Regex(args(shift))  
  49.     val files = args.drop(shift + 1)  
  50.     for (f <- files) {  
  51.       var linenum = 0  
  52.       try {  
  53.         for (line <- Source.fromFile(f).getLines()) {  
  54.           linenum += 1  
  55.           var mat = pattern findFirstIn line  
  56.           if (mat == None) {  
  57.             if (o_invert) {  
  58.               if (o_plinen) printf("%d: ", linenum)  
  59.               println(line)  
  60.             }  
  61.           }  
  62.           else {  
  63.             if (!o_invert) {  
  64.               if (o_plinen) printf("%d: ", linenum)  
  65.               println(line)  
  66.             }  
  67.           }  
  68.         }  
  69.       } catch {  
  70.         case e: FileNotFoundException => printf("File %s not found\n", f)  
  71.         case e: IOException => printf("Cannot read %s\n", f)  
  72.       }  
  73.     }  
  74.   }  
  75. }  

No comments:

Post a Comment