Command Line Arguments in Racket
Command-line arguments are a common way to parameterize execution of programs. For example, racket hello.rkt
uses hello.rkt
as an argument to the racket
program.
#lang racket
(define (main)
; `current-command-line-arguments` provides access to raw command-line
; arguments. Note that this vector does not include the program name.
(define args-without-prog (vector->list (current-command-line-arguments)))
; To get the program name, we can use `find-system-path`
(define prog-name (path->string (find-system-path 'run-file)))
; Combine program name with arguments
(define args-with-prog (cons prog-name args-without-prog))
; You can get individual args with normal list indexing.
; Be careful to check the length of the list first!
(define arg (if (>= (length args-without-prog) 3)
(list-ref args-without-prog 2)
""))
(printf "~a\n" args-with-prog)
(printf "~a\n" args-without-prog)
(printf "~a\n" arg))
(main)
To experiment with command-line arguments, it’s best to save this code in a file (e.g., command-line-arguments.rkt
) and run it with the racket
command:
$ racket command-line-arguments.rkt a b c d
("/path/to/command-line-arguments.rkt" "a" "b" "c" "d")
("a" "b" "c" "d")
c
In Racket, command-line arguments are accessed through the current-command-line-arguments
function, which returns a vector of strings. We convert this to a list for easier manipulation.
Unlike in some languages, the program name is not included in the command-line arguments in Racket. We can get it separately using (find-system-path 'run-file)
.
We demonstrate how to access individual arguments, but note that in Racket, it’s important to check the length of the argument list before accessing elements to avoid errors.
Next, we’ll look at more advanced command-line processing with parsing options.