Parse command-line arguments: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(28 intermediate revisions by 18 users not shown)
Line 8:
Many languages provide a library (getopt or GetOpt) to parse the raw command line options in an intelligent way.
<br><br>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">
-- Show command-line arguments
-- J. Carter 2023 Apr
-- The task is called "Parse command-line arguments", but as parsing requires attaching meaning to arguments, and the task
-- specification does not do so, showing them is all we can reasonably do
 
with Ada.Command_Line;
with Ada.Text_IO;
 
procedure Show_Args is
-- Empty
begin -- Show_Args
All_Args : for Arg in 1 .. Ada.Command_Line.Argument_Count loop
Ada.Text_IO.Put_Line (Item => Arg'Image & ": " & Ada.Command_Line.Argument (Arg) );
end loop All_Args;
end Show_Args;
</syntaxhighlight>
 
{{out}}
<pre>
$ ./show_args nc -v -n -z -w 1 192.168.1.2 1-1000
1: nc
2: -v
3: -n
4: -z
5: -w
6: 1
7: 192.168.1.2
8: 1-1000
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">loop.with:'i arg 'a ->
print ["argument" (to :string i)++":" a]
 
loop args [k,v]->
if k <> "values" ->
print ["found option:" k "with value:" v "(of type:" (to :string type v)++")"]</syntaxhighlight>
 
'''Sample input:'''
 
<pre>arturo parse\ command-line\ arguments.art one two --file:four --verbose --loop:3 three</pre>
 
'''Sample output:'''
 
<pre>argument 0: one
argument 1: two
argument 2: --file:four
argument 3: --verbose
argument 4: --loop:3
argument 5: three
found option: file with value: four (of type: string)
found option: verbose with value: true (of type: logical)
found option: loop with value: 3 (of type: integer)</pre>
 
=={{header|AutoHotkey}}==
For AutoHotkey v1.1+
<langsyntaxhighlight AutoHotkeylang="autohotkey">;Get Arguments as an array
if 0 > 0
{
Line 41 ⟶ 98:
}
 
MsgBox % "Parsed Arguments :`n" msg</langsyntaxhighlight>
'''Output (MsgBox):'''
<pre>Parsed Arguments :
Line 52 ⟶ 109:
=={{header|AWK}}==
{{works with|gawk}}
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -E
# -E instead of -f so program arguments don't conflict with Gawk arguments
@include "getopt.awk"
Line 70 ⟶ 127:
if(tval) print "-t = " tval
if(uval) print "-u = " uval
}</langsyntaxhighlight>
 
=={{header|Bracmat}}==
Line 80 ⟶ 137:
=={{header|C}}==
The man page for getopt (man 3 getopt) provides better option handling with examples. But if you just want to parse one argument... (adapted from simple database task):
<langsyntaxhighlight lang="c">#include <stdio.h>
int main(int argc, char **argv){
int i;
Line 109 ⟶ 166:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
See [https://github.com/clojure-cookbook/clojure-cookbook/blob/master/03_general-computing/3-07_parse-command-line-arguments.asciidoc Parsing Command-Line Arguments] from O'Reilly's Clojure Cookbook github.
 
=={{header|D}}==
The [http://dlang.org/phobos/std_getopt.html getopt module] in D's standard library is inspired by Perl's Getopt::Long module. The syntax of Phobos getopt infers the expected parameter types from the static types of the passed-in pointers.
<langsyntaxhighlight lang="d">import std.stdio, std.getopt;
 
void main(string[] args) {
Line 134 ⟶ 191:
writeln("verbose: ", verbose);
writeln("color: ", color);
}</langsyntaxhighlight>
{{out|Usage example}}
<pre>C:\getopt_test --verbose --length 12
Line 141 ⟶ 198:
verbose: true
color: no</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
<syntaxhighlight lang="delphi">
program Parse_command_line_argument;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils;
 
var
sfile, sLength: string;
verbose: boolean;
 
begin
if (ParamCount = 0) or (FindCmdLineSwitch('h', true)) then
begin
Writeln('Usage: -file {filename} -l {length} {-v}'#10);
Writeln('* filename: Name of file to process. Default "file.dat";');
Writeln('* length: Max number of bytes to read (not optional);');
Writeln('* -v (verbose): show information on terminal. Default "false"');
end
else
begin
Assert(FindCmdLineSwitch('l', sLength), 'Length is not optional');
 
if not FindCmdLineSwitch('file', sfile) then
sfile := 'file.dat';
 
verbose := FindCmdLineSwitch('v', True);
 
Writeln('Variables states:'#10);
Writeln('File: ', sfile);
Writeln('Verbose: ', verbose);
Writeln('Length: ', sLength);
end;
 
Readln;
end.</syntaxhighlight>
{{out}}
Parse_command_line_argument.exe
<pre>
Usage: -file {filename} -l {length} {-v}
 
* filename: Name of file to process. Default "file.dat";
* length: Max number of bytes to read (not optional);
* -v (verbose): show information on terminal. Default "false"</pre>
Parse_command_line_argument.exe -file main.c -v -l 10
<pre>
Variables states:
 
File: main.c
Verbose: TRUE
Length: 10</pre>
=={{header|Elixir}}==
Elixir provides an option parser in a library module called <tt>OptionParser</tt>.
 
<langsyntaxhighlight lang="elixir">#!/usr/bin/env elixir
IO.puts 'Arguments:'
IO.inspect OptionParser.parse(System.argv())</langsyntaxhighlight>
 
<langsyntaxhighlight lang="bash">$ ./parse-args.exs --a --b --c=yes --no-flag --verbose -V -a=1 -b=t -- apple banana
Arguments:
{[a: true, b: true, c: "yes", no_flag: true, verbose: true],
["apple", "banana"], [{"-V", nil}, {"-a", "1"}, {"-b", "t"}]}</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' Program (commandline.exe) invoked like this:
Line 172 ⟶ 282:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 191 ⟶ 301:
=={{header|Go}}==
Most simply, implementing the suggested example from the talk page:
<langsyntaxhighlight lang="go">package main
 
import (
Line 206 ⟶ 316:
fmt.Println("s:", *s)
fmt.Println("n:", *n)
}</langsyntaxhighlight>
Example runs:
<pre>
Line 228 ⟶ 338:
The Icon Programming Library provides a procedure for processing command line options. See the library reference for detailed documentation. The code below is an example.
 
<langsyntaxhighlight Iconlang="icon">link options
 
procedure main(ARGLIST)
Line 241 ⟶ 351:
i := opttable(i) # assign an integer
...
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 256 ⟶ 366:
:Test if an argument is present:
 
::<langsyntaxhighlight lang="j"> (<'-b') e. ARGV</langsyntaxhighlight>
 
::This is true if the argument is present and false, if it is not.
Line 262 ⟶ 372:
:Or, find the name of an optional file:
 
::<langsyntaxhighlight lang="j"> (ARGV i.<'-f') {:: }.ARGV,a:</langsyntaxhighlight>
 
::This is the name of the first file named after the first -f argument, or empty if there was no such file.
Line 268 ⟶ 378:
Other concepts are also possible...
 
=={{header|Mathematicajq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq'''
 
The jq and gojq programs parse some command-line options and arguments for their own purposes
but also provide two mechanisms allowing for arbitrarily many command-line arguments to be provided to the program:
 
* the --args option can be used to provide a sequence of shell strings that are converted to JSON strings;
* the --jsonargs option can similarly be used to specify a sequence of JSON values.
 
For example, assuming a bash or bash-like shell, the invocation
<pre>
jq -n '$ARGS' --args 1 two '[3, "four"]'
</pre>
results in:
<pre>
{
"positional": [
"1",
"two",
"[3, \"four\"]"
],
"named": {}
}
</pre>
whereas:
<pre>
jq -n '$ARGS' --jsonargs 1 '"two"' '[3, "four"]'
</pre>
results in:
<pre>
{
"positional": [
1,
"two",
[
3,
"four"
]
],
"named": {}
}
</pre>
 
Notice that in the first case, the token `two` has not been quoted, whereas in the second case, it must be presented as `'"two"'`
if it is to be understood as a JSON string.
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
Example taken from the official documentation of [https://carlobaldassi.github.io/ArgParse.jl/stable/ ArgParse docs].
 
<syntaxhighlight lang="julia">using ArgParse
 
function parse_commandline()
s = ArgParseSettings()
 
@add_arg_table s begin
"--opt1"
help = "an option with an argument"
"--opt2", "-o"
help = "another option with an argument"
arg_type = Int
default = 0
"--flag1"
help = "an option without argument, i.e. a flag"
action = :store_true
"arg1"
help = "a positional argument"
required = true
end
 
return parse_args(s)
end
 
function main()
parsed_args = parse_commandline()
println("Parsed args:")
for (arg,val) in parsed_args
println(" $arg => $val")
end
end
 
main()</syntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.0.6 (packaged as parse_cla.jar)
 
fun main(args: Array<String>) = println(args.asList())</syntaxhighlight>
 
{{out}}
<pre>
c:\kotlin-compiler-1.0.6>java -jar parse_cla.jar nc -v -n -z -w 1 192.168.1.2 1-1000
[nc, -v, -n, -z, -w, 1, 192.168.1.2, 1-1000]
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The command line is parsed and stored into a list of strings to ease manual handling by list processing functions.
<syntaxhighlight lang="mathematica">$CommandLine
<lang Mathematica>
-> {math, -v, -n, -z, -w, 1, 192.168.1.2, 1-1000}</syntaxhighlight>
$CommandLine
 
-> {math, -v, -n, -z, -w, 1, 192.168.1.2, 1-1000}
=={{header|Nim}}==
</lang>
<syntaxhighlight lang="nim">import os
import parseopt
 
proc main =
# Directly accessing the app name and parameters
echo "app name: ", getAppFilename().extractFilename()
echo "# parameters: ", paramCount()
for ii in 1 .. paramCount(): # 1st param is at index 1
echo "param ", ii, ": ", paramStr(ii)
 
echo ""
 
# Using parseopt module to extract short and long options and arguments
var argCtr : int
 
for kind, key, value in getOpt():
case kind
of cmdArgument:
echo "Got arg ", argCtr, ": \"", key, "\""
argCtr.inc
of cmdLongOption, cmdShortOption:
case key
of "v", "n", "z", "w":
echo "Got a \"", key, "\" option with value: \"", value, "\""
else:
echo "Unknown option: ", key
 
of cmdEnd:
discard
 
 
main()
</syntaxhighlight>
 
Sample command line:
<pre>
parsecmdline ab -z cd ef -w=abcd --w=1234 -v -e -x 1-1000
</pre>
 
Output:
<pre>
app name: parsecmdline
# parameters: 10
param 1: ab
param 2: -z
param 3: cd
param 4: ef
param 5: -w=abcd
param 6: --w=1234
param 7: -v
param 8: -e
param 9: -x
param 10: 1-1000
 
Got arg 0: "ab"
Got a "z" option with value: ""
Got arg 1: "cd"
Got arg 2: "ef"
Got a "w" option with value: "abcd"
Got a "w" option with value: "1234"
Got a "v" option with value: ""
Unknown option: e
Unknown option: x
Got arg 3: "1-1000"
</pre>
 
=={{header|Nu}}==
Parsing can be done through the <code>main</code> function's signature.
<syntaxhighlight lang="nu">
def main [
input: string # File to operate on
output?: string # File to write to
--verbose (-v): # Be verbose
] {
{
Input: $input
Output: $output
Verbose: $verbose
}
}
</syntaxhighlight>
{{out}}
<pre>
~> nu cli.nu input.txt --verbose
╭─────────┬───────────╮
│ Input │ input.txt │
│ Output │ │
│ Verbose │ true │
╰─────────┴───────────╯
~> nu cli.nu input.txt output.txt
╭─────────┬────────────╮
│ Input │ input.txt │
│ Output │ output.txt │
│ Verbose │ false │
╰─────────┴────────────╯
~> nu cli.nu --invalid
Error: nu::parser::unknown_flag
 
× The `main` command doesn't have flag `invalid`.
╭─[<commandline>:1:1]
1 │ main --invalid
· ────┬────
· ╰── unknown flag
╰────
help: Available flags: --verbose(-v), --help(-h). Use `--help` for more information.
 
~> nu cli.nu --help
Usage:
> cli.nu {flags} <input> (output)
 
Flags:
-v, --verbose - Be verbose
-h, --help - Display the help message for this command
 
Parameters:
input <string>: File to operate on
output <string>: File to write to (optional)
 
Input/output types:
╭───┬───────┬────────╮
│ # │ input │ output │
├───┼───────┼────────┤
│ 0 │ any │ any │
╰───┴───────┴────────╯
</pre>
 
=={{header|PARI/GP}}==
GP exists in a REPL and so it doesn't make sense to parse command-line arguments. But PARI can parse them just like [[#C|C]]:
<langsyntaxhighlight lang="c">#include <pari/pari.h>
#include <stdio.h>
 
Line 283 ⟶ 615:
pari_printf("8 + 1 = %Ps\n", addii(int2u(3), gen_1));
return 0;
}</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 289 ⟶ 621:
Use the <tt>Getopt::Long</tt> module:
 
<langsyntaxhighlight lang="perl"># Copyright Shlomi Fish, 2013 under the MIT/X11 License.
 
use strict;
Line 308 ⟶ 640:
($verbose ? "Verbosity" : "No verbosity"),
" and a length of $length.\n";
</syntaxhighlight>
</lang>
 
The output from it is:
Line 323 ⟶ 655:
</pre>
 
=={{header|Perl 6Phix}}==
{{libheader|Phix/basics}}
At the end of running any top-level code (which can preprocess the arguments if it likes), Perl 6 automatically examines any remaining arguments and transforms them into a call to a <tt>MAIN</tt> routine, if one is defined. The arguments are parsed based on the signature of the routine, so that options are mapped to named arguments.
 
<lang perl6>sub MAIN (Bool :$b, Str :$s = '', Int :$n = 0, *@rest) {
<!--<syntaxhighlight lang="phix">(phixonline)-->
say "Bool: $b";
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
say "Str: $s";
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">command_line</span><span style="color: #0000FF;">()</span>
say "Num: $n";
<span style="color: #0000FF;">?</span><span style="color: #000000;">res</span>
say "Rest: @rest[]";
<!--</syntaxhighlight>-->
}</lang>
 
{{out}}
Interpreted: res[1] is the interpreter, res[2] the source
<pre>$ ./main -h
<pre>
Usage:
> p ./maintest [-b]nc [-s=<Str>]v [-n=<Int>] [<rest>-z -w 1 192.168.1.]2 1-1000
{"C:\\Program Files (x86)\\Phix\\p.exe","C:\\Program Files (x86)\\Phix\\test.exw","nc","-v","-n","-z","-w","1","192.168.1.2","1-1000"}
</pre>
Compiled: both res[1] and res[2] are the executable
<pre>
> p -c test nc -v -n -z -w 1 192.168.1.2 1-1000
{"C:\\Program Files (x86)\\Phix\\test.exe","C:\\Program Files (x86)\\Phix\\test.exe","nc","-v","-n","-z","-w","1","192.168.1.2","1-1000"}
> test nc -v -n -z -w 1 192.168.1.2 1-1000
{"C:\\Program Files (x86)\\Phix\\test.exe","C:\\Program Files (x86)\\Phix\\test.exe","nc","-v","-n","-z","-w","1","192.168.1.2","1-1000"}
</pre>
pwa/p2js: There is no real command line, you always get a length-2 {"p2js",href} pair:
<pre>
{"p2js","file:///C:/Program%20Files%20(x86)/Phix/pwa/test.htm"}
</pre>
 
=={{header|Picat}}==
$ ./main -b -n=42 -s=turtles all the way down
Picat has no built-in option parser, so the user must write a specific for each use case. The arguments to a Picat programs are available via <code>main/1</code> as a list of strings.
Bool: True
Str: turtles
Num: 42
Rest: all the way down</pre>
If there are multiple <tt>MAIN</tt> subs, they are differentiated by multiple dispatch. A help message can automatically be generated for all the variants. The intent of this mechanism is not to cover every possible switch structure, but just to make it drop-dead easy to handle most of the common ones.
 
Here is a simple variant which parse the arguments and just puts the parameters into a map where the key is the position of the parameter and the value is:
=={{header|Python}}==
Version 2.3+
<lang Python>
from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
 
* [parameter argument] for <code>-name argument</code>
(options, args) = parser.parse_args()
* [parameter, true] for <code>-flag</code>
* [parameter,""] for <code>parameter</code>
 
example:
 
<syntaxhighlight lang="picat">main(ARGS) =>
<yourscript> --file=outfile -q
Opts = new_map(),
</lang>
process_args(ARGS,Opts),
foreach(Pos=V in Opts)
println(Pos=V)
end,
nl.
main(_) => true.
 
 
process_args(ARGS,Opts) :-
process_args(ARGS,1,Opts).
 
process_args([],_Pos,_Map).
 
process_args(["-x"|As],Pos,Map) :-
Map.put(Pos,[verbose,true]),
process_args(As,Pos+1,Map).
process_args(["-n"|As],Pos,Map) :-
Map.put(Pos,[numbers,true]),
process_args(As,Pos+1,Map).
process_args(["-z"|As],Pos,Map) :-
Map.put(Pos, [zebra,true]),
process_args(As,Pos+1,Map).
 
process_args(["-w",Arg|As],Pos,Map) :-
Map.put(Pos,[walking,Arg]),
process_args(As,Pos+1,Map).
 
process_args([Opt|As],Pos,Map) :-
Map.put(Pos,[Opt,'']),
process_args(As,Pos+1,Map).</syntaxhighlight>
 
Note: The parameters to the program should not be one of Picat's own parameters, since they will be parsed (and consumed) by Picat before starting to run the user's program. Here are Picat's parameters:
<pre>-g goal
--help
--v, -v, --version
-b B size of the trail stack
-log, -l
-p P size of program area
-path P
-s S size of stack/heap</pre>
 
Thus the flag <code>-v</code> cannot be used as a parameter to the program; instead <code>-x</code> is used.
 
{{out}}
<pre>$ picat command_line_arguments.pi nc -x -n -z -w 1 192.168.1.2 1-1000
1 = [nc,]
2 = [verbose,true]
3 = [numbers,true]
4 = [zebra,true]
5 = [walking,1]
6 = [192.168.1.2,]
7 = [1-1000,]</pre>
 
=={{header|PicoLisp}}==
PicoLisp doesn't have a library to get options. Instead, the command line is parsed at startup and handled in the following way: Each command line argument is executed (interpreted) as a Lisp source file, except that if the first character is a hypen '-', then that arguments is taken as a Lisp function call (without the surrounding parentheses). For example, the command line
<langsyntaxhighlight lang="shell">$ ./pil abc.l -foo def.l -"bar 3 4" -'mumble "hello"' -bye</langsyntaxhighlight>
has the effect that
# The file "abc.l" is executed
Line 378 ⟶ 765:
=={{header|PowerShell}}==
Powershell functions and filters handle options organically, with advanced .NET support to handle complex and advanced options including aliases, ranges, sets, datatypes, and more. [https://msdn.microsoft.com/en-us/powershell/reference/5.0/microsoft.powershell.core/about/about_parsing See] [https://msdn.microsoft.com/powershell/reference/5.1/Microsoft.PowerShell.Core/about/about_Functions more] [https://msdn.microsoft.com/en-us/powershell/reference/5.0/microsoft.powershell.core/about/about_functions_advanced here]. However, to parse options 'classically', you can write a custom parser. A slightly messy version (inspired by ruby optparse) that can only handle switches and relies on RegEx:
<syntaxhighlight lang="powershell">
<lang Powershell>
$options = @{
opt1 = [bool] 0
Line 430 ⟶ 817:
return [array]$argv,$options
}#fn
</syntaxhighlight>
</lang>
Usage (in some function or script):
<syntaxhighlight lang="powershell">
<lang Powershell>
 
$argv,$options = parseOptions $args $options
Line 440 ⟶ 827:
$bar = $argv | SomeOtherFilter | Baz
}
</syntaxhighlight>
</lang>
Usage in shell:
<langsyntaxhighlight lang="shell">
$> function -c --wwxx arg1 arg2
</syntaxhighlight>
</lang>
Note that this works in Powershell. All of the arguments after the function name will be passed as strings to the function, which then calls them as an array with the automatic variable, $args. The custom parser/function does the work from there, turning the strings into flags and typed arguments. WARNING: This is reinventing the wheel to an extreme degree.
 
=={{header|Prolog}}==
Works in SWI-Prolog.
 
<syntaxhighlight lang="prolog">:- initialization(main, main).
 
main(Argv) :-
opt_spec(Spec),
opt_parse(Spec, Argv, Opts, _),
(
member(help(true), Opts) -> show_help
; maplist(format('~w~n'), Opts)
).
show_help :-
opt_spec(Spec),
opt_help(Spec, HelpText),
write('Usage: swipl opts.pl <options>\n\n'),
write(HelpText).
opt_spec([
[opt(help),
type(boolean),
default(false),
shortflags([h]),
longflags([help]),
help('Show Help')],
[opt(noconnect),
type(boolean),
default(false),
shortflags([n]),
longflags([noconnect]),
help('do not connect, just check server status')],
[opt(server),
type(atom),
default('www.google.com'),
shortflags([s]),
longflags([server]),
help('The server address.')],
[opt(port),
type(integer),
default(5000),
shortflags([p]),
longflags([port]),
help('The server port.')]
]).</syntaxhighlight>
 
{{out}}
<syntaxhighlight lang="powershell">
# no options set (use defaults)
$ swipl .\opts.pl
help(false)
noconnect(false)
server(www.google.com)
port(5000)
 
# setting various options
$ swipl .\opts.pl --server www.test.com -p 2342 -n
help(false)
server(www.test.com)
port(2342)
noconnect(true)
 
# show help
$ swipl .\opts.pl -h
Usage: swipl opts.pl <options>
 
--help -h boolean=false Show Help
--noconnect -n boolean=false do not connect, just check server status
--server -s atom=www.google.com The server address.
--port -p integer=5000 The server port.
</syntaxhighlight>
 
=={{header|Python}}==
Version 2.3+
<syntaxhighlight lang="python">
from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
 
(options, args) = parser.parse_args()
 
example:
 
<yourscript> --file=outfile -q
</syntaxhighlight>
 
=={{header|Racket}}==
Line 451 ⟶ 932:
Racket has a good command-line parsing library, the following demonstrates some of its features:
 
<langsyntaxhighlight lang="racket">
#!/usr/bin/env racket
#lang racket
Line 481 ⟶ 962:
(printf "Log level: ~s\n" loglevel)
(printf "Operations: ~a\n" (string-join ops ", ")))
</syntaxhighlight>
</lang>
 
Sample runs:
Line 512 ⟶ 993:
Operations: add, add, edit, delete
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
At the end of running any top-level code (which can preprocess the arguments if it likes), Raku automatically examines any remaining arguments and transforms them into a call to a <tt>MAIN</tt> routine, if one is defined. The arguments are parsed based on the signature of the routine, so that options are mapped to named arguments.
<syntaxhighlight lang="raku" line>sub MAIN (Bool :$b, Str :$s = '', Int :$n = 0, *@rest) {
say "Bool: $b";
say "Str: $s";
say "Num: $n";
say "Rest: @rest[]";
}</syntaxhighlight>
{{out}}
<pre>$ ./main -h
Usage:
./main [-b] [-s=<Str>] [-n=<Int>] [<rest> ...]
 
$ ./main -b -n=42 -s=turtles all the way down
Bool: True
Str: turtles
Num: 42
Rest: all the way down</pre>
If there are multiple <tt>MAIN</tt> subs, they are differentiated by multiple dispatch. A help message can automatically be generated for all the variants. The intent of this mechanism is not to cover every possible switch structure, but just to make it drop-dead easy to handle most of the common ones.
 
=={{header|REXX}}==
Line 537 ⟶ 1,039:
╚═════════════════════════════════════════════════════════════════════════════╝
</pre>
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates one method to parse options for a command (entered on the CL*/
parse arg opts /*this preserves the case of options. */
opts=space(opts) /*elide superfluous blanks in options. */
Line 576 ⟶ 1,078:
isInt: return datatype(arg(1), 'W') /*return 1 if argument is an integer*/
isNum: return datatype(arg(1), 'N') /*return 1 if argument is a number.*/
sayer: say; say '***error***' arg(1); exit 13</langsyntaxhighlight>
<pre>
╔═══════════════════════════════════════════════════════════════════════╗
Line 593 ⟶ 1,095:
 
=== Ruby with 'getoptlong' ===
<langsyntaxhighlight lang="ruby">#!/usr/bin/env ruby
 
# == Synopsis
Line 674 ⟶ 1,176:
nil
end
end</langsyntaxhighlight>
 
<pre>$ ./pargs.rb -h
Line 708 ⟶ 1,210:
 
=== Ruby with 'optparse' ===
<langsyntaxhighlight lang="ruby">require 'optparse'
 
sflag = false
Line 759 ⟶ 1,261:
Fruit: #{fruit}
Arguments: #{ARGV.inspect}
EOF</langsyntaxhighlight>
 
<pre>$ ruby takeopts.rb -h
Line 786 ⟶ 1,288:
Fruit: orange
Arguments: ["-arg"]</pre>
 
=={{header|Rust}}==
 
Using the [https://docs.rs/structopt StructOpt]:
 
<syntaxhighlight lang="rust">use structopt::StructOpt;
 
#[derive(StructOpt)]
struct Opt {
#[structopt(short)]
b: bool,
#[structopt(short, required = false, default_value = "")]
s: String,
#[structopt(short, required = false, default_value = "0")]
n: i32,
}
 
fn main() {
let opt = Opt::from_args();
println!("b: {}", opt.b);
println!("s: {}", opt.s);
println!("n: {}", opt.n);
}</syntaxhighlight>
 
Examples:
 
<pre>
> parse
b: false
s:
n: 0
 
> parse -s bye -b
b: true
s: bye
n: 0
 
> parse -n 99 -s "say my name"
b: false
s: say my name
n: 99
</pre>
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">object CommandLineArguments extends App {
println(s"Received the following arguments: + ${args.mkString("", ", ", ".")}")
}</langsyntaxhighlight>
 
=={{header|Standard ML}}==
Line 797 ⟶ 1,341:
{{works with|MLton}}
The following code listing can be compiled with both [[SML/NJ]] and [[MLton]]:
<langsyntaxhighlight lang="sml">structure Test = struct
 
exception FatalError of string
Line 828 ⟶ 1,372:
 
(* MLton *)
val _ = Test.main (CommandLine.name(), CommandLine.arguments())</langsyntaxhighlight>
 
=== SML/NJ ===
[[SML/NJ]] can compile source code to a "heap file", witch can than be executed by the interpreter with arguments given (see [http://stackoverflow.com/questions/5053149/sml-nj-how-to-compile-standalone-executable this entry on stackowerflow.com] for more information).
The <code>source.cm</code> file should lock like this:
<syntaxhighlight lang="text">Group
is
SOURCE_FILE.sml
$/basis.cm</langsyntaxhighlight>
To compile the program, use <code>ml-build sources.cm</code>. This should create a "heap file" <code>sources.x86-linux</code>, depending on your architecture.
The heap file can be executed with <code>sml @SMLload=sources.x86-linux ARGUMENTS</code>, or the script [http://www.smlnj.org/doc/heap2exec/index.html <code>heap2exec</code>] can be used to make a single executable.
Line 845 ⟶ 1,389:
=={{header|Tcl}}==
The following proc detects and removes argument-less (-b) and one-argument options from the argument vector.
<langsyntaxhighlight Tcllang="tcl">proc getopt {_argv name {_var ""} {default ""}} {
upvar 1 $_argv argv $_var var
set pos [lsearch -regexp $argv ^$name]
Line 857 ⟶ 1,401:
return 0
}
}</langsyntaxhighlight>
Usage examples:
getopt argv -sep sep ";" ;# possibly override default with user preference
Line 864 ⟶ 1,408:
Searching with -regexp allows to specify longer mnemonic names, so it still succeeds on longer flags, e.g.
$ myscript.tcl -separator '\t' ...
 
=={{header|Wren}}==
Any command line arguments passed to a Wren CLI script are collected in the same order into a list of strings. If individual arguments require any further parsing, this can then be done using normal Wren code.
<syntaxhighlight lang="wren">import "os" for Process
 
var args = Process.arguments
System.print("The arguments passed are: %(args)")
// parse last argument to a Range object
var sp = args[-1].split("-")
var start = Num.fromString(sp[0])
var end = Num.fromString(sp[1])
var r = start..end
System.print("The final argument expressed as a Range object is %(r)")</syntaxhighlight>
 
{{out}}
<pre>
$ wren_cli Parse_command-line_arguments.wren -v -n -z -w 1 192.168.1.2 1-1000
 
The arguments passed are: [-v, -n, -z, -w, 1, 192.168.1.2, 1-1000]
The final argument expressed as a Range object is 1..1000
</pre>
 
=={{header|XPL0}}==
<pre>parseargs nc -v -n -z -w 1 192.168.1.2 1-1000</pre>
<syntaxhighlight lang "XPL0">int N, C;
[N:= 0;
loop [C:= ChIn(8);
if C = $0D \CR\ then quit;
N:= N+1;
CrLf(0); IntOut(0, N); Text(0, ": ");
repeat ChOut(0, C);
C:= ChIn(8);
until C = $20 \space\;
];
CrLf(0);
]</syntaxhighlight>
{{out}}
<pre>
 
1: nc
2: -v
3: -n
4: -z
5: -w
6: 1
7: 192.168.1.2
8: 1-1000
</pre>
 
=={{header|zkl}}==
Line 869 ⟶ 1,461:
 
File myprogram.zkl:
<langsyntaxhighlight lang="zkl">var ip;
argh := Utils.Argh(
T("v","v","print version",fcn{println("Version stub")}),
Line 884 ⟶ 1,476:
case("z") { println("zazzle") }
}
}</langsyntaxhighlight>
<pre>zkl myprogram nc -v -n -z --ip 192.168.1.2 1-1000</pre>
{{out}}
9,476

edits