From 7a06385ccfc61b01e82b0939979c0a5afe384bdf Mon Sep 17 00:00:00 2001
From: Mark McGranaghan
package main
import (
"bufio"
"fmt"
- "io"
"os"
"strings"
)
@@ -85,14 +84,14 @@ pattern to write your own Go line filters.
Wrapping the unbuffered os.Stdin
with a buffered
-reader gives us a convenient ReadString
method
-that we’ll use to read input line-by-line.
+scanner gives us a convenient Scan
method that
+advances the scanner to the next token; which is
+the next line in the default scanner.
- rdr := bufio.NewReader(os.Stdin)
- out := os.Stdout
+ scanner := bufio.NewScanner(os.Stdin)
@@ -100,16 +99,13 @@ that we’ll use to read input line-by-line.
- ReadString
returns the next string from the
-input up to the given separator byte. We give the
-newline byte '\n'
as our separator so we’ll get
-successive input lines.
+ Text
returns the current token, here the next line,
+from the input.
- for {
- switch line, err := rdr.ReadString('\n'); err {
+ for scanner.Scan() {
@@ -117,19 +113,11 @@ successive input lines.
- 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.
-
+
- case nil:
- ucl := strings.ToUpper(line)
- if _, err = out.WriteString(ucl); err != nil {
- fmt.Fprintln(os.Stderr, "error:", err)
- os.Exit(1)
- }
+ ucl := strings.ToUpper(scanner.Text())
@@ -137,14 +125,13 @@ error on this write as we do on the read.
- The EOF
error is expected when we reach the
-end of input, so exit gracefully in that case.
+ Write out the uppercased line.
- case io.EOF:
- os.Exit(0)
+ fmt.Println(ucl)
+ }
@@ -152,16 +139,15 @@ end of input, so exit gracefully in that case.
- Otherwise there’s a problem; print the
-error and exit with non-zero status.
+ Check for errors during Scan
. End of file is
+expected and not reported by Scan
as an error.
- default:
- fmt.Fprintln(os.Stderr, "error:", err)
- os.Exit(1)
- }
+ if err := scanner.Err(); err != nil {
+ fmt.Fprintln(os.Stderr, "error:", err)
+ os.Exit(1)
}
}