Last active
August 29, 2015 14:14
-
-
Save oylenshpeegul/3cbe264c87fc425be4b9 to your computer and use it in GitHub Desktop.
Emulate Perl's diamond operator in Go.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 liketotalLineCount
rather thanfileLineCount
.