4

There are many Perl tutorials explaining how to use GetOptions utility to process only the command-line arguments which are expected, else exit with an appropriate message.

In my requirement I have following optional command-line arguments, like,

  • -z zip_dir_path : zip the output
  • -h : show help.

I tried few combinations with GetOptions which did not work for me.
So my question is: How to use GetOptions to handle this requirement?

EDIT: -z needs 'zip directory path'

EDIT2: My script has following compulsory command-line arguments:

  • -in input_dir_path : Input directory
  • -out output_dir_path : Output directory

Here's my code:

my %args;
GetOptions(\%args,
"in=s",
"out=s"
) or die &usage();

die "Missing -in!" unless $args{in};
die "Missing -out!" unless $args{out};

Hope this EDIT adds more clarity.

TheCottonSilk
  • 8,662
  • 2
  • 26
  • 37
  • 3
    Usually you call `GetOptions` and then look at what you end up with to see which switches were used. Maybe you should include a few of your attempts to clarify what's going on and what the problem is. – mu is too short Jul 02 '11 at 07:31
  • @mu is too short: I have updated the question text. Thank you for comment. – TheCottonSilk Jul 02 '11 at 07:38

3 Answers3

9

A : (colon) can be used to indicate optional options:

#!/usr/bin/env perl

use strict;
use warnings;

use Getopt::Long;

my ( $zip, $help, $input_dir, $output_dir );

GetOptions(
    'z:s'   => \$zip,
    'h'     => \$help,
    'in=s'  => \$input_dir,
    'out=s' => \$output_dir,
);
mu is too short
  • 426,620
  • 70
  • 833
  • 800
Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127
  • I think, ':' can be used to indicate the string value for that command-line switch is optional, and not for indicating that the switch itself is optional. Am I right? – TheCottonSilk Jul 02 '11 at 09:05
  • Although I have accepted `@Alan Haggai Alavi`'s answer, agree with `@mu is too short` in his comment that GetOptions is used to list the options provided by the user and the script has to process the arguments further as per need. – TheCottonSilk Jul 02 '11 at 11:29
4

From the documentation:

   : 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.

If you specify that and check for the empty string, you know which ones the user did not specify.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
2

This should set to 1 or 0 the values of $zip_output and $show_help based on what input arguments you get in command line.

use strict;
use warnings;

use Getopt::Long;

my $zip_output;
my $show_help;

GetOptions("z" => \$zip, "h" => \$show_help);
Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127
Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72