命令行参数解析精粹

1. C语言版
用到getopt_long这个函数, 代码如下:

/******************************************************************************
 * \File
 *  main.c
 * \Brief
 * 
 * \Author
 *  Hank
 * \Created date
 *  2013-03-12
 ******************************************************************************
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>

extern char *optarg;
extern int opterr;
struct option opts[] = {
  {"ip", required_argument, NULL, 'i'},
  {"port", required_argument, NULL, 'p'},
  {"host", required_argument, NULL, 's'},
  {"out" , required_argument, NULL, 'o'},
  {"help", required_argument, NULL, 'h'},
  {0,0,0,0}
};

int parse_params(int argc, char** argv, char* ip, int* port, char* host, char* f);

int main(int argc, char* argv[])
{
  char ip[32] = "225.1.1.31";
  int port = 1234;
  char host[32] = "127.0.0.1";
  char filename[512] = "udp.dat";

  /*Parsing command-line parameters */ 
  parse_params(argc, argv, ip, &port, host, filename); 
                                                                                         
                                                                                         
  return 0; 


int parse_params(int argc, char** argv, 

      char* ip, int* port, char* host, char* f) 

  int c, index;

  opterr = 0; 
  while ((c = getopt_long(argc, argv, "i:p:s:o:h", opts, NULL)) != -1) 
  {
    switch (c) 
    {
      case 'i': 
        strcpy(ip, optarg); 
        break; 
      case 'p': 
        *port = atoi(optarg); 
        break; 
      case 's': 
        strcpy(host, optarg); 
        break; 
      case 'o': 
        strcpy(f, optarg); 
        break; 
      case 'h': 
      default: 
        printf("Usage: \n"); 
        printf("-i ip : set udp's ip address\n"); 
        printf("-p port : set udp's port\n"); 
        printf("-s host : set local addresss\n"); 
        printf("-o file : set output filename\n"); 
        printf("-h : print help information\n"); 
        return 1; 
      } 
  } 
                                                                                                                                                               
  /* show banner */ 
  printf("ip : %s \nport : %d \nhost : %s \nfile : %s\n", 
        ip, *port, host, f); 
                                                                                                                                                               
  for (index = optind; index < argc; index++) 
    printf("Non-option argument %s\n", argv[index]); 
                                                                                                                                                               
  return 0; 
}


2. Perl语言版
使用Getopt::Long模块:
http://search.cpan.org/~jv/Getopt-Long-2.39/lib/Getopt/Long.pm


代码如下:
#!/usr/bin/perl
##############################################################################
# \File
#   parseing_args.pl
# \Brief
#
# \Author
#  Hank
# \Created date
#  2013-03-14
##############################################################################
use Getopt::Long;

my ($params, $key, $verbose, $help);

my $argc = $#ARGV;               # 输入参数的个数
my $result = GetOptions("params|p=s" => \$params,
                        "key|k=i"    => \$key,
                        "verbose"    => \$verbose,
                        "help"       => \$help);
if($help == 1 || $argc == -1)
{
  print "Usage:\n";
  print "./parsing_args.pl --params=\"...\" --key=1234 --verbose\n";
  exit -1;
}

print "PARAMS: ", $params, "\n";
print "MSG_KEY:", $key,"\n";
print "VERBOSE:", $verbose,   "\n";

参数不区分大小写, --H --h 都行。
一些参数的说明:

!   : 
  The option does not take an argument and may be negated by prefixing it with "no" or "no-". 
   E.g.  "foo!" 
     will allow --foo (a value of 1 will be assigned) 
     as well as --nofoo and --no-foo (a value of 0 will be assigned). 
  If the option has aliases, this applies to the aliases as well.
  Using negation on a single letter option when bundling is in effect is pointless and will result in a warning.

+   :
  The option does not take an argument and will be incremented by 1 every time it appears on the command line. 
  E.g. "more+", 
    when used with --more --more --more,
    will increment the value three times, resulting in a value of 3 (provided it was 0 or undefined at first).

  The + specifier is ignored if the option destination is not a scalar.

= type [ desttype ] [ repeat ]
  The option requires an argument of the given type. Supported types are:

s  :
  String. 
  An arbitrary sequence of characters. 
  It is valid for the argument to start with - or --.

i  :
  Integer. 
  An optional leading plus or minus sign, followed by a sequence of digits.

o  :
  Extended integer, Perl style. 
  This can be either an optional leading plus or minus sign, followed by a sequence of digits, 
  or an octal string (a zero, optionally followed by '0', '1', .. '7'), 
  or a hexadecimal string (0x followed by '0' .. '9', 'a' .. 'f', case insensitive), 
  or a binary string (0b followed by a series of '0' and '1').

f  :
  Real number. 
  For example 3.14, -6.23E24 and so on.

  The desttype can be @ or % to specify that the option is list or a hash valued. 
  This is only needed when the destination for the option value is not otherwise specified. 
  It should be omitted when not needed.

  The repeat specifies the number of values this option takes per occurrence on the command line. 
  It has the format:
     { [ min ] [ , [ max ] ] }.

    min      denotes the minimal number of arguments. 
             It defaults to 1 for options with = and to 0 for options with :, 
             see below. Note that min overrules the = / : semantics.


    max      denotes the maximum number of arguments. 
             It must be at least min. If max is omitted, but the comma is not, 
             there is no upper bound to the number of argument values taken.


: type [ desttype ]
   Like =, 
   but designates the argument as optional. 
   If omitted, an empty string will be assigned to string values options, and the value zero to numeric options.

   Note that if a string argument starts with - or --, it will be considered an option on itself.

: number [ desttype ]
   Like :i, 
   but if the value is omitted, the number will be assigned.

: + [ desttype ]
   Like :i, 
   but if the value is omitted, the current value for the option will be incremented.

你可能感兴趣的:(arguments,getopt,command-line)