← Cookbook Basics Beginner · Pooka 0.5.0

Read command-line arguments

Read the words typed after your program's name, and let a match decide what they mean.

You will use

  • pooka/env: env.args() returns the arguments as a List(String)
  • match on lists, with pattern alternatives for options in either order
  • pooka/process: process.exit(1) when the arguments make no sense

The whole program

src/main.pooka
module main

import pooka/env
import pooka/io
import pooka/process
import pooka/string

usage() -> String {
  "usage: greet <name> [--shout]"
}

greet(arguments: List(String)) -> Result(String, String) {
  match arguments {
    [name] -> Ok("Hello, " + name + ".")
    [name, "--shout"] | ["--shout", name] -> Ok(
      string.uppercase("Hello, " + name + "!")
    )
    [] -> Error(usage())
    _ -> Error("too many arguments\n" + usage())
  }
}

main() {
  match greet(env.args()) {
    Ok(line) -> {
      io.println(line)
      Nil
    }
    Error(message) -> {
      io.eprintln(message)
      process.exit(1)
    }
  }
}

Run it

Arguments for your program go after --, so pooka knows they are not for itself:

$ pooka run -- Ada
Hello, Ada.
$ pooka run -- Ada --shout
HELLO, ADA!
$ pooka run
usage: greet <name> [--shout]

How it works

  1. Arguments are a list. env.args() gives you every word after --, as strings, without the program's own name.
  2. Each shape is a case. One name, a name with --shout, nothing at all, or too much. The arm [name, "--shout"] | ["--shout", name] accepts the option before or after the name, and both alternatives bind name.
  3. Deciding is separate from doing. greet returns a Result and prints nothing, so it is easy to test. main prints the line, or prints the usage to standard error and exits with status 1, so scripts can tell something went wrong.

Try next: add a --times N option and parse the number with Parse a number safely. For anything bigger, a small argument-parsing library will save you from writing every arm by hand.