- Command-line argument parsing
-
Different Command-line argument parsing methods are used by different programming languages to parse command-line arguments.
Contents
Programming languages
C
Main article: C_syntax#Command-line_argumentsC uses
argv
to process command-line arguments.[1]Java
An example of Java argument parsing would be:
public class Echo { public static void main (String[] args) { for (String s: args) { System.out.println(s); } } }
Perl
Perl uses
$ARGV
.PHP
PHP uses
argc
as a count of arguments andargv
as an array containing the values of the arguments.[2][3] To create an array from command-line arguments in the-foo:bar
format, the following might be used:$args = parseArgs( $argv ); echo getArg( $args, 'foo' ); function parseArgs( $args ) { foreach( $args as $arg ) { $tmp = explode( ':', $arg, 2 ); if( $arg[0] == "-" ) { $args[ substr( $tmp[0], 1 ) ] = $tmp[1]; } } return $args; } function getArg( $args, $arg ) { if( isset( $args[$arg] ) ) { return $args[$arg]; } return false; }
PHP can also use
getopt()
[4]Python
Python uses
sys.argv
, e.g.:import sys for arg in sys.argv: print arg
Racket
Racket uses a
current-command-line-arguments
parameter, and provides aracket/cmdline
[5] library for parsing these arguments. Example:#lang racket (require racket/cmdline) (define smile? #true) (define nose? #false) (define eyes ":") (command-line #:program "emoticon" #:once-any ; the following two are mutually exclusive [("-s" "--smile") "smile mode" (set! smile? #true)] [("-f" "--frown") "frown mode" (set! smile? #false)] #:once-each [("-n" "--nose") "add a nose" (set! nose? #true)] [("-e" "--eyes") char "use <char> for the eyes" (set! eyes char)]) (printf "~a~a~a\n" eyes (if nose? "-" "") (if smile? ")" "("))
The library parses long and short flags, handles arguments, allows combining short flags, and handles
-h
and--help
automatically:$ racket /tmp/c -nfe 8 8-(
References
- ^ "The C Book — Arguments to main". Publications.gbdirect.co.uk. http://publications.gbdirect.co.uk/c_book/chapter10/arguments_to_main.html. Retrieved 2010-05-31.
- ^ "PHP Manual". PHP. http://php.net/manual/en/reserved.variables.argv.php. Retrieved 2010-05-31.
- ^ wikibooks:PHP Programming/CLI
- ^ http://php.net/getopt
- ^ The Racket reference manual, Command-Line Parsing
Categories:- Command shells
- Articles with example Java code
- Articles with example PHP code
- Articles with example Racket code
Wikimedia Foundation. 2010.