Search code examples
perlgetopt-long

How to use Getopt::Long method?


How can I use Getopt::Long method if the input command execution is like this:

$ testcmd -option check  ARG1 ARG2 ARG3

or

$ testcmd  ARG1 ARG2 ARG3

Solution

  • A quick example:

    #! /usr/bin/perl
    
    use warnings;
    use strict;
    
    use Getopt::Long;
    
    sub usage { "Usage: $0 [--option=VALUE] ARG1 ARG2 ARG3\n" }
    
    my $option = "default";
    
    GetOptions("option=s", \$option)
      or die usage;
    
    die usage unless @ARGV == 3;
    
    print "$0: option=$option: @ARGV\n";
    

    Getopt::Long is quite flexible in what it will accept:

    $ ./cmd
    Usage: ./cmd [--option=VALUE] ARG1 ARG2 ARG3
    
    $ ./cmd 1 2 3
    ./cmd: option=default: 1 2 3
    
    $ ./cmd --option=foo 4 5 6
    ./cmd: option=foo: 4 5 6
    
    $ ./cmd -option=bar 7 8 9
    ./cmd: option=bar: 7 8 9
    
    $ ./cmd -option check a b c
    ./cmd: option=check: a b c