Created
January 15, 2012 16:17
PLEAC: File Access (Scala)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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