Command-line argument parsing

Different Command-line argument parsing methods are used by different programming languages to parse command-line arguments.

Programming languages

C

C uses argv to process command-line arguments.[1][2]

An example of C argument parsing would be:

#include <stdio.h>
int main (int argc, char *argv[])
{
    int count;
    for (count=0; count<argc; count++)
        puts (argv[count]);
}

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);
        }
    }
}

Bash

Bash uses $1 $2 ... ($0 is the script filename).

echo $1
echo $2
...

or

for p in "$@"
do
    echo $p
done

Perl

Perl uses $ARGV.

foreach $arg (@ARGV)
{
    print $arg;
}

or

foreach $argnum (0 .. $#ARGV)
{
   print $ARGV[$argnum];
}

AWK

AWK uses ARGV also.

BEGIN {
   for ( i = 0; i < ARGC; i++ )
   {
       print ARGV[i]
   }
}

PHP

PHP uses argc as a count of arguments and argv as an array containing the values of the arguments.[3][4] 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().[5]

Python

Python uses sys.argv, e.g.:

import sys
for arg in sys.argv:
    print arg

Python also has a module called argparse in the standard library for parsing command-line arguments.[6]

Racket

Racket uses a current-command-line-arguments parameter, and provides a racket/cmdline[7] library for parsing these arguments. Example:

#lang racket

(require racket/cmdline)

(define smile? (make-parameter #t))
(define nose?  (make-parameter #false))
(define eyes   (make-parameter ":"))

(command-line #:program "emoticon"

              #:once-any ; the following two are mutually exclusive
              [("-s" "--smile") "smile mode" (smile? #true)]
              [("-f" "--frown") "frown mode" (smile? #false)]

              #:once-each
              [("-n" "--nose") "add a nose"  (nose? #true)]
              [("-e" "--eyes") char "use <char> for the eyes" (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

This article is issued from Wikipedia - version of the 11/24/2015. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.