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

匿名

发表评论

匿名网友