Update line-filters.go to use bufio Scanner.

Same functionality, just using go 1.1+ API convenience of bufio Scanners.
This commit is contained in:
Matt Horsnell 2013-12-16 09:43:05 +00:00
parent e4b2d0add1
commit 5b13535069

View File

@ -11,7 +11,6 @@ package main
import ( import (
"bufio" "bufio"
"fmt" "fmt"
"io"
"os" "os"
"strings" "strings"
) )
@ -19,38 +18,24 @@ import (
func main() { func main() {
// Wrapping the unbuffered `os.Stdin` with a buffered // Wrapping the unbuffered `os.Stdin` with a buffered
// reader gives us a convenient `ReadString` method // scanner gives us a convenient `Scan` method that
// that we'll use to read input line-by-line. // advances the scanner to the next token; which is
rdr := bufio.NewReader(os.Stdin) // the next line in the default scanner.
out := os.Stdout scanner := bufio.NewScanner(os.Stdin)
// `ReadString` returns the next string from the for scanner.Scan() {
// input up to the given separator byte. We give the // `Text` returns the current token, here the next line,
// newline byte `'\n'` as our separator so we'll get // from the input.
// successive input lines. ucl := strings.ToUpper(scanner.Text())
for {
switch line, err := rdr.ReadString('\n'); err { // Write out the uppercased line.
fmt.Println(ucl)
// If the read succeeded (the read `err` is nil), }
// write out out the uppercased line. Check for an
// error on this write as we do on the read. // Check for errors during `Scan`. End of file is
case nil: // expected and not reported by `Scan` as an error.
ucl := strings.ToUpper(line) if err := scanner.Err(); err != nil {
if _, err = out.WriteString(ucl); err != nil { fmt.Fprintln(os.Stderr, "error:", err)
fmt.Fprintln(os.Stderr, "error:", err) os.Exit(1)
os.Exit(1)
}
// The `EOF` error is expected when we reach the
// end of input, so exit gracefully in that case.
case io.EOF:
os.Exit(0)
// Otherwise there's a problem; print the
// error and exit with non-zero status.
default:
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
} }
} }