/* -*- scala -*- */ /* hello world */ /* print a simple string on stdout */ println("Hello World") /* argv */ /* access command line parameters (no segmentation fault accepted, nor silent exception, so some languages must explicitly check the presence of the argument) */ println(args(0)) /* env */ /* access environment variable */ println(System getenv "HOME") /* test file exists */ /* return exit code error (non zero) if a file does not exist */ if(!new java.io.File("/etc/mtab").exists) exit(1) /* test file readable */ /* return exit code error (non zero) if a file is not readable */ if(!new java.io.File("/etc/mtab").canRead) exit(1) /* formatting */ /* print integers in a simple formatted string */ val (a, b) = (1, 2) println(a + " + " + b + " = " + (a + b)) /* system */ /* call an external program and check the return value */ def exec = Runtime.getRuntime.exec(_:String) if (exec("false").waitFor > 0) error("false failed") new io.BufferedSource(exec("echo done").getInputStream) foreach print /* sed in place */ /* remove #-comments from a file (modifying the file, i.e. in place) */ val i = io.Source.fromFile(args(0)).mkString val w = new java.io.FileWriter(args(0)) w write i.replaceAll("#.*\n","") w.close /* compile what must be */ /* find and compile .c files into .o when the .o is old or absent */ for (s <- new java.io.File(args(0)).listFiles if ""+s endsWith ".c") { val o = new java.io.File((""+s dropRight 1)+"o") if (!o.exists || o.lastModified < s.lastModified) { println("compiling "+s+" to "+o) Runtime.getRuntime.exec("gcc -c " + s + " -o " + o) } } /* grep */ /* grep with -F -i -h handling, usage, grep'ing many files */ val options = "-([hiF]+)".r val (optList, pattern :: files) = args.toList span (options.pattern matcher _ matches) val opts = optList.map{ case options(x) => x }.mkString.toSet if (args.isEmpty || opts('h')) { println("usage: grep [-F] [-i] regexp [files...]") exit(1) } val mods = Map('i' -> ("(?i)" + _), 'F' -> (java.util.regex.Pattern.quote(_))) .filterKeys(opts) .withDefaultValue((x: String) => x) val regex = mods('i')(mods('F')(pattern)).r files foreach { file => io.Source fromFile file getLines () foreach { line => regex findFirstIn line foreach { _ => if (files.size > 1) print(file+":") println(line) } } }