Skip to content

Instantly share code, notes, and snippets.

@oylenshpeegul
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oylenshpeegul/3cbe264c87fc425be4b9 to your computer and use it in GitHub Desktop.
Save oylenshpeegul/3cbe264c87fc425be4b9 to your computer and use it in GitHub Desktop.
Emulate Perl's diamond operator in Go.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
filenames := []string{"-"}
if len(os.Args) > 1 {
filenames = os.Args[1:]
}
totalLineCount := 0
for _, filename := range filenames {
var file *os.File
var err error
if filename == "-" {
file = os.Stdin
} else {
if file, err = os.Open(filename); err != nil {
fmt.Fprintln(os.Stderr, err)
continue
}
defer file.Close()
}
fileLineCount := 0
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fileLineCount++
totalLineCount++
line := scanner.Text()
// do something with line here
fmt.Printf("%d (%d): %s\n", fileLineCount, totalLineCount, line)
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, err)
continue
}
}
}
@oylenshpeegul
Copy link
Author

Perl is also keeping track of the line number in $. automatically; we'd have to do that ourselves if we cared. But it doesn't reset for the next file, so it would be like totalLineCount rather than fileLineCount.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment