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

17,970

Solution 1

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

Solution 2

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.

Solution 3

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);
Share:
17,970
TheCottonSilk
Author by

TheCottonSilk

Enjoy being in the Android, Linux World!

Updated on June 04, 2022

Comments

  • TheCottonSilk
    TheCottonSilk about 2 years

    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
    TheCottonSilk almost 13 years
    @'Tudor Constantin': I have updated my question text. Thank you for the answer.
  • TheCottonSilk
    TheCottonSilk almost 13 years
    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
    TheCottonSilk almost 13 years
    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.