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

There are many Perl tutorials that explain how to use the GetOptions utility to process only the command line arguments that are expected, otherwise exit with the appropriate message.

In my requirement, I have the following optional command line arguments, e.g.

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

I tried several combinations with GetOptions that did not work for me.
So my question is: how to use GetOptions to fulfill this requirement?

EDIT: -z needs a zip zip directory path

EDIT2: My script has the following required command line arguments:

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

Here is 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}; 

We hope this EDIT adds more clarity.

+4
source share
3 answers

A : (colon) can be used to indicate additional 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, ); 
+9
source

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 this and check for an empty string, you know which ones the user did not specify.

+3
source

This should indicate 1 or 0 values โ€‹โ€‹of $zip_output and $show_help based on the input arguments that you enter on the command line.

 use strict; use warnings; use Getopt::Long; my $zip_output; my $show_help; GetOptions("z" => \$zip, "h" => \$show_help); 
+2
source

All Articles