Go行過濾器實例

線過濾器是一種常見類型的程序,它讀取stdin上的輸入,處理它,然後將一些派生結果打印到stdoutgrepsed是常用的行過濾器。

這裏是一個示例行過濾器,將寫入所有輸入文本轉換爲大寫。可以使用此模式來編寫自己的Go行過濾器。

所有的示例代碼,都放在 F:\worksp\golang 目錄下。安裝Go編程環境請參考:http://www.yiibai.com/go/go\_environment.html

line-filters.go的完整代碼如下所示 -

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func main() {

    // Wrapping the unbuffered `os.Stdin` with a buffered
    // scanner gives us a convenient `Scan` method that
    // advances the scanner to the next token; which is
    // the next line in the default scanner.
    scanner := bufio.NewScanner(os.Stdin)

    for scanner.Scan() {
        // `Text` returns the current token, here the next line,
        // from the input.
        ucl := strings.ToUpper(scanner.Text())

        // Write out the uppercased line.
        fmt.Println(ucl)
    }

    // Check for errors during `Scan`. End of file is
    // expected and not reported by `Scan` as an error.
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "error:", err)
        os.Exit(1)
    }
}

執行上面代碼,將得到以下輸出結果 -

F:\worksp\golang>go run line-filters.go
this is a Line filters demo by yiibai.com
THIS IS A LINE FILTERS DEMO BY YIIBAI.COM
yes
YES
No
NO