Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 357
Tree Avatar asked Dec 01 '25 06:12

Tree


1 Answers

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
like image 94
Greg Bacon Avatar answered Dec 02 '25 20:12

Greg Bacon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!