Categories
Golang regex

Golang Programming Language. Reading files to get deeper.

I am going to drop a snippet to introduce some cool concepts about the Golang Programming Language that may help you to see its coolness and maybe adopt it by yourself.

I am going to use regex, buffered IO, defered close, and handle errors for all of this in less than 60 lines with comments.

Comments may guide you, but any question can be answered to me about this code. Duckduckgo may also help you if you are not into doing that social thing.

package main

// Not say the import syntax is not cool.
import (
        "bufio"
        "fmt"
        "os"
        "regexp"
)

func main() {
        // The path to the file.
        path := "hola"
        // Opening the file.
        buffer, err := os.Open(path)
        // Error handling.
        if err != nil {
                dief("Unable to open file %s: %s", path, err.Error())
        }
        // We make this function execute on function return, expected or unexpected.
        defer func() {
                // Closing the buffer.
                err = buffer.Close()
                if err != nil {
                        dief("Unable to close buffer: %s", err.Error())
                }
        }()
        // Regexes are a useful tool to introduce.
        re, err := regexp.Compile("hola.")
        if err != nil {
                dief("Regexp failed to compile, malformed regex: %s", err.Error())
        }

        scanner := bufio.NewScanner(buffer)
        line_number := 1
        // Conditional for loop, works like while in other languages.
        for scanner.Scan() {
                this_line := scanner.Text()
                // In multiline arguments , is required also for the last argument.
                // The compiler expects , or ) not newline. :)
                fmt.Printf(
                        "Found hola %d times in line %d of %s\n",
                        len(re.FindAllString(this_line, -1)),
                        line_number,
                        path,
                )
        }
}

// Variadic arguments to a die helper function.
func dief(format_string string, args ...interface{}) {
        // We can pass variadic arguments to other functions which is pretty useful sometimes.
        fmt.Fprintf(os.Stderr, format_string+"\n", args...)
        os.Exit(1)
}

Here is some example content for the hola file we are reading.

holae huteoauhshthola hola ete hola
hola 
hola
holatttthola

And its example output, may differ since I left trailing whitespace sometimes in the file on purpose, but clipboard and WordPress may have omited it.

Found hola 3 times in line 1 of hola
Found hola 1 times in line 1 of hola
Found hola 0 times in line 1 of hola
Found hola 1 times in line 1 of hola

By sergiotarxz

I am a software developer with high interest on free software.

Leave a Reply

Your email address will not be published. Required fields are marked *