github.com/benhoyt/goawk@v1.8.1/interp/example_test.go (about) 1 // Don't run these on Windows, because newline handling means they 2 // don't pass (TODO: report a Go bug?) 3 4 //go:build !windows 5 // +build !windows 6 7 package interp_test 8 9 import ( 10 "bytes" 11 "fmt" 12 "strings" 13 14 "github.com/benhoyt/goawk/interp" 15 "github.com/benhoyt/goawk/parser" 16 ) 17 18 func Example() { 19 input := bytes.NewReader([]byte("foo bar\n\nbaz buz")) 20 err := interp.Exec("$0 { print $1 }", " ", input, nil) 21 if err != nil { 22 fmt.Println(err) 23 return 24 } 25 // Output: 26 // foo 27 // baz 28 } 29 30 func Example_fieldsep() { 31 // Use ',' as the field separator 32 input := bytes.NewReader([]byte("1,2\n3,4")) 33 err := interp.Exec("{ print $1, $2 }", ",", input, nil) 34 if err != nil { 35 fmt.Println(err) 36 return 37 } 38 // Output: 39 // 1 2 40 // 3 4 41 } 42 43 func Example_program() { 44 src := "{ print NR, tolower($0) }" 45 input := "A\naB\nAbC" 46 47 prog, err := parser.ParseProgram([]byte(src), nil) 48 if err != nil { 49 fmt.Println(err) 50 return 51 } 52 config := &interp.Config{ 53 Stdin: bytes.NewReader([]byte(input)), 54 Vars: []string{"OFS", ":"}, 55 } 56 _, err = interp.ExecProgram(prog, config) 57 if err != nil { 58 fmt.Println(err) 59 return 60 } 61 // Output: 62 // 1:a 63 // 2:ab 64 // 3:abc 65 } 66 67 func Example_funcs() { 68 src := `BEGIN { print sum(), sum(1), sum(2, 3, 4), repeat("xyz", 3) }` 69 70 parserConfig := &parser.ParserConfig{ 71 Funcs: map[string]interface{}{ 72 "sum": func(args ...float64) float64 { 73 sum := 0.0 74 for _, a := range args { 75 sum += a 76 } 77 return sum 78 }, 79 "repeat": strings.Repeat, 80 }, 81 } 82 prog, err := parser.ParseProgram([]byte(src), parserConfig) 83 if err != nil { 84 fmt.Println(err) 85 return 86 } 87 interpConfig := &interp.Config{ 88 Funcs: parserConfig.Funcs, 89 } 90 _, err = interp.ExecProgram(prog, interpConfig) 91 if err != nil { 92 fmt.Println(err) 93 return 94 } 95 // Output: 96 // 0 1 9 xyzxyzxyz 97 }