[comp.lang.perl] usage.pl

utashiro@sran84.sra.co.jp (Kazumasa Utashiro) (03/16/91)

This is a perl library to generate a usage string which is
used combined with &Getopts function.

					--utashiro@sra.co.jp

#!/usr/local/bin/perl
require('getopts.pl');
#require('usage.pl');
$option = 'deg:u:s:';
@arglist = (
	'd::debug',
	'g:group',
	'u:user:user name',
);
&Getopts($option);
print &Usage($0, $option, 'file ...', @arglist);
exit;

;#------------------------------------------------------------
;# usage.pl: make a string for usage line.
;#	by K. Utashiro <utashiro@sra.co.jp> on Fri Sep 7 1990
;#	Revised by utashiro on Sat Mar 16 1991
;#
;# Syntax: &Usage($command, $option, $trailer, @arglist);
;#	$command: command name (maybe $0)
;#	$option:  option string same as &Getopt
;#	$trailer: trailer string (optional)
;#	@arglist: description for options which takes argument (optional)
;#		  format is "option character : argument : description"
;#		  where argument and description are optional
;#
;# &Usage returns list of two strings where 1st string is for usage
;# line and 2nd is for description.
;#
;# Example:
;#	$option = 'deg:u:s:';
;#	@arglist = ('d::debug', 'g:group', 'u:user:user name');
;#	unless (&Getopts($option)) {
;#		print &Usage($0, $option, 'file ...', @arglist);
;#		exit(1);
;#	}
;#
;# Result:
;#	usage: sample [ -d ] [ -e ] [ -g group ] [ -u user ] [ -s : ] file ...
;#		-d       debug
;#		-u user  user name
;#
sub Usage {
    package usage;
    local($cmd, $opt, $trailer, @arglist, %optarg) = @_;
    for(@arglist) {
	($name, $arg, $desc) = split(/:/, $_, 3);
	$optarg{$name} = $arg if $arg;
	$optdesc{$name} = $desc if $desc;
    }
    $cmd =~ s#.*/##;
    local(@list) = ("usage:", $cmd);
    while ($opt =~ /^\s*(.)(:?)/) {
	push(@list, "[", "-$1");
	$2 && push(@list, $optarg{$1} || $2);
	push(@list, "]");
	$opt = $';
    }
    push(@list, "$trailer\n");
    $usage = join(' ', @list);

    if (defined(%optdesc)) {
	for(keys %optdesc) {
	    $l = length($optarg{$_});
	    $max < $l && ($max=$l);
	}
	$format = sprintf("\t-%%s %%-%ds  %%s\n", $max);
	for(sort keys %optdesc) {
	    $description .= sprintf($format, $_, $optarg{$_}, $optdesc{$_});
	}
    }
    ($usage, $description);
}
1;
;#------------------------------------------------------------