#!/usr/bin/guile \ -e main -s !# ; ; prototype skeleton for a classic unix-style filter written in guile. ; We accept a collection of command-line arguments, ; and print a usage message ; (use-modules (ice-9 getopt-long) (ice-9 format)) (define usage "usage: process-file [options] file ... options: -D|--debug enable debugging output -h|--help print this message -p|--prepend P prepend P to each line processed -v|--verbose enable debugging output") ; specification of command-line options for use by getopt-long (define optspec `( (debug (single-char #\D)) (prepend (single-char #\p) (value #t)) (verbose (single-char #\v)) (help (single-char #\h)) )) ; global flags and their default values (define g-verbose #f) (define g-debug #f) (define (main argv) (let ((opts ; catch any exception of type misc-error that might be thrown ; by getopt-long if the user gives a bogus option. ; if we catch one, print the original error message (which says ; what was wrong) and then print the usage message and exit. (catch 'misc-error (lambda () (getopt-long argv optspec)) (lambda (key args . rest) (apply display-error #f (current-error-port) args rest) (format (current-error-port) "~a\n" usage) (exit 1))))) (set! g-debug (option-ref opts 'debug #f)) (set! g-verbose (option-ref opts 'verbose #f)) (if g-debug (format #t "~d files: ~s l=~d\n" (length (option-ref opts '() '())) (option-ref opts '() '()))) (if (option-ref opts 'help #f) (begin (format #t "~a\n" usage) (exit 0))) (if (> 1 (length (option-ref opts '() '()))) (begin (format (current-error-port) "process-file: ERROR: no file specified; use - for stdin\n") (exit 1) )) ; iterate over the non-option arguments (for-each (lambda (fname) (if (string=? fname "-") (process-lines (current-input-port) (option-ref opts 'prepend "")) (let* ((fp (open-file fname "r"))) (process-lines fp (option-ref opts 'prepend "")) (close-port fp) ))) (option-ref opts '() '())) ) ) ; this subroutine does the real work on each file to be processed. (define (process-lines fp prefix) (if g-debug (format #t "process-lines fp=~s prefix=~s\n" fp prefix)) (do ((line (read-line fp) (read-line fp))) ((eof-object? line)) (format #t "\"~a\"\n" (string-append prefix line)) ))