Ed Heal
Ed Heal

Reputation: 59997

Getopt::Long - How to get script arguments that are not options

Taken from the manual page Getopt::Long:

The code is:

use Getopt::Long;
my $data   = "file.dat";
my $length = 24;
my $verbose;
GetOptions ("length=i" => \$length,    # numeric
            "file=s"   => \$data,      # string
            "verbose"  => \$verbose)   # flag
or die("Error in command line arguments\n");

And I execute the script thus:

./myscript.pl --verbose filename.txt

How do I get hold of the argument filename.txt?

Upvotes: 1

Views: 1005

Answers (3)

TLP
TLP

Reputation: 67900

To quote the original question:

Taken from the manual page: Getopt::Long

Mixing command line option with other arguments

Usually programs take command line options as well as other arguments, for example, file names. It is good practice to always specify the options first, and the other arguments last. Getopt::Long will, however, allow the options and arguments to be mixed and 'filter out' all the options before passing the rest of the arguments to the program. To stop Getopt::Long from processing further arguments, insert a double dash -- on the command line:

--size 24 -- --all

In this example, --all will not be treated as an option, but passed to the program unharmed, in @ARGV.

Upvotes: 1

lordadmira
lordadmira

Reputation: 1832

Non option arguments are simply left in @ARGV.

our $argument = shift @ARGV;

There is a more concise way to use Getopt though. By specifying a hash reference as the first argument, all of the options are assigned to that hash. It's a great way to keep all of the options together in one place. The option spec can be put into a qw list.

use strict;
use diagnostics;
use Getopt::Long;

## %options must be declared seperately because it is referenced in its own definition
our %options;
%options = (
  # set default debug level
  debug => 0,
  # set default file name
  file => "file.dat",
  # option with multi-effects, setting debug and verbose at once
  quiet => sub { @options{qw/debug verbose/} = (0, 0); },
  loud  => sub { @options{qw/debug verbose/} = (999, 1); },
);

GetOptions(\%options, qw/debug+ verbose! file=s length=o quiet loud/);

our $argument = shift @ARGV;
die "missing first argument\n" unless defined $argument;

print "Starting program $0 on $argument\n" if $options{verbose};
if ($options{debug} >= 2) {
  ## Load this module only if we need it, but you must guarantee it's there or trap the error with eval{}
  require Data::Dump;
  printf "Dumping options hash\n%s\n", Data::Dump::pp(\%options);
}

Upvotes: 3

ikegami
ikegami

Reputation: 385657

Non-options are left in @ARGV.

This means you can simply use <> to read from them if they're file names.

Upvotes: 5

Related Questions