3

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
Ether
  • 53,118
  • 13
  • 86
  • 159
Tree
  • 9,532
  • 24
  • 64
  • 83
  • 2
    That depends on what you want to have done with those options and flags. The people who answer below are trying to make their best guess, but mind-reading is a difficult skill to master. – Ether Jun 30 '10 at 16:15

3 Answers3

4

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
Greg Bacon
  • 134,834
  • 32
  • 188
  • 245
4

You need to enable the pass_through option. Documentation quoted below:

pass_through (default: disabled)

Options that are unknown, ambiguous or supplied with an invalid option value are passed through in @ARGV instead of being flagged as errors. This makes it possible to write wrapper scripts that process only part of the user supplied command line arguments, and pass the remaining options to some other program.

If require_order is enabled, options processing will terminate at the first unrecognized option, or non-option, whichever comes first. However, if permute is enabled instead, results can become confusing.

DVK's posted an example of how to do this in another answer. I'd upvote his answer first if you find it useful.

Community
  • 1
  • 1
Zaid
  • 36,680
  • 16
  • 86
  • 155
1
#!/usr/bin/perl

use Getopt::Long;

my $cla = GetOptions (  "one=s"         =>      \$one,
                        "two=s"         =>      \$two,
                        "three=s"       =>      \$three,
                        "help|h|?"      =>      \$help,
) or usage ();

if ($help) {
        usage ();
}

my $first = $one;
my $second = $two;
my $third = $three;

printf ("%-7s %-9s %-7s\n", $first, $second, $third);

sub usage {
        print "\n$0\t" . "[ -one <text> -two <text> -three <text> ]\n\n";
        exit (0);
}