Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use GetOptions utility to handle 'optional' command-line arguments in Perl?

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.

like image 923
TheCottonSilk Avatar asked Dec 07 '22 20:12

TheCottonSilk


2 Answers

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,
);
like image 140
Alan Haggai Alavi Avatar answered May 16 '23 07:05

Alan Haggai Alavi


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.

like image 40
brian d foy Avatar answered May 16 '23 09:05

brian d foy