Day98: Scala

Posted by csiu on June 2, 2017 | with: 100daysofcode

Today I want to mess with Scala and be able to do the following:

Task

For each line in a data file, I want to generate standard code around that line. If this line matches some regular expression, I want to then add a few more things to that output.

Purpose

To learn how to programs in Scala.

(and because I sort of need to know this/ it would be a great help for my day job)

Getting started

To execute script “my_script.scala”, you need to run:
scala /path/to/my_script.scala

To start, we need to learn the Scala syntax for each component of the task:

// 1. Check that the script works by printing "Hello..."
println("Hello from the script")
// 2. Be able to access terminal arguments when you run
//        scala path/to/my_script.scala first_arg
println("This is my first argument: " + args(0))
// 3. Check that the first argument is a file
//    and do something if it is
val input_file = args(0)

import java.nio.file.{Paths, Files}
val isFile = Files.exists(Paths.get(input_file))

if (isFile) {
  println(f"'$input_file' is a file")
}
else {
  println(f"'$input_file' is not a file")
  System.exit(1)
}
// 4. Read a file line by line
scala.io.Source.fromFile(input_file).getLines().foreach {
  println
}
// 5. Define a function to produce a string
//    and be able to use it
def template(input_string: String) : String = {
  var blurb : String = f"Hello $input_string"
  return blurb;
}

// Use function
println(template("John Smith"))
// 6. Read a file line by line,
//    assign the line to a variable,
//    and use the line in a function
for (line <- scala.io.Source.fromFile(input_file).getLines()) {
  println(template(line))
}
// 7. Do something if a string matches some regex
val regrex_berry = """berry""".r

for (line <- scala.io.Source.fromFile(input_file).getLines()) {
  val isMatchLine = regrex_berry.findFirstIn(line).isDefined

  if (isMatchLine) {
    println(f"'$line' is a berry")
  }
}


Putting it all together

Now that we have all the pieces, we can assemble the script: