Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@toddsundsted
Created January 15, 2012 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toddsundsted/1616304 to your computer and use it in GitHub Desktop.
Save toddsundsted/1616304 to your computer and use it in GitHub Desktop.
PLEAC: File Access (Scala)
/* File Access
* see http://pleac.sourceforge.net/pleac_perl/fileaccess.html
* Scala 2.9.1
*/
import scripting.file._
import scripting.file.Implicits._
/* Introduction */
// scala/java regex do not match substrings, as do languages like perl and ruby
io.Source.fromFile("/usr/local/widgets/data").getLines.foreach { line =>
if (".*(blue).*".r.pattern.matcher(line).matches)
println(line)
}
val Blue = ".*(blue).*".r
io.Source.fromFile("/usr/local/widgets/data").getLines.foreach { line =>
line match {
case Blue(blue) => println(line)
case _ =>
}
}
// getLine() on Source is deprecated; if you need to explicitly open a file
// and read lines you can drop into Java-land...
import java.io.{File, DataInputStream, FileInputStream}
val file = new File("/usr/local/widgets/data")
val dis = new DataInputStream(new FileInputStream(file))
while (dis.available > 0) {
val = dis.readLine
line match {
case Blue(blue) => println(line)
case _ =>
}
}
val Digit = ".*(\\d).*".r
Source.stdin.getLines.foreach { line => // reads from STDIN
line match {
case Digit(digit) => Console.out.println("Read: " + line) // writes to STDOUT
case _ => Console.err.println("No digit found") // writes to STDERR
}
}
import java.io.FileOutputStream
val logfile = "log.txt".f
val fos = new FileOutputStream(logfile)
Console.withOut(fos) { // switch to logfile for output
println("Countdown initiated ...")
} // return to original output
println("You have 30 seconds to reach minimum safety distance.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment