Command Line Arguments in Chapel

Command-line arguments are a common way to parameterize execution of programs. For example, ./myProgram arg1 arg2 uses arg1 and arg2 as arguments to the myProgram executable.

use IO;

proc main(args: [] string) {
  // The `args` array provides access to raw command-line arguments.
  // Note that the first value in this array is the path to the program,
  // and `args[1..]` holds the arguments to the program.
  var argsWithProg = args;
  var argsWithoutProg = args[1..];

  // You can get individual args with normal indexing.
  var arg = args[3];

  writeln(argsWithProg);
  writeln(argsWithoutProg);
  writeln(arg);
}

To experiment with command-line arguments, it’s best to compile the program first.

$ chpl command_line_arguments.chpl -o command_line_arguments
$ ./command_line_arguments a b c d
[./command_line_arguments a b c d]       
[a b c d]
c

In Chapel, command-line arguments are passed to the main procedure as an array of strings. The program name is included as the first element of this array, similar to many other programming languages.

The use IO; statement at the beginning imports the necessary module for input/output operations, allowing us to use the writeln procedure for printing to the console.

Chapel’s arrays are zero-based by default, but we can use array slicing (args[1..]) to get all elements from index 1 onwards, effectively removing the program name from the arguments list.

Next, we’ll look at more advanced command-line processing with configuration variables, which are Chapel’s equivalent to command-line flags in other languages.