Search code examples
perlcommand-line-argumentsgetopt-long

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.


Solution

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