Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a string with GetOpt::Long::GetOptions?

I have a string with possible command line arguments (using an Read-Eval-Print-Loop program) and I want it to be parsed similar to the command line arguments when passed to Getopt::Long.

To elaborate:

I have a string

$str = '--infile /tmp/infile_location --outfile /tmp/outfile'

I want it to be parsed by GetOptions so that it is easier for me to add new options.

One workaround I could think of is to split the string on whitespace and replace @ARGV with new array and then call GetOptions. something like ...

my @arg_arr = split (/\s/, $input_line);

# This is done so that GetOptions reads these new arguments
@ARGV = @arg_arr;
print "ARGV is : @ARGV\n";
GetOptions (
            'infile=s'  => \$infile,
            'outfile=s' => \$outfile
           );

Is there any good/better way?

like image 354
Jagmal Avatar asked Sep 22 '08 23:09

Jagmal


People also ask

How do I use Getopt long in Perl?

To use Getopt::Long from a Perl program, you must include the following line in your Perl program: use Getopt::Long; This will load the core of the Getopt::Long module and prepare your program for using it. Most of the actual Getopt::Long code is not loaded until you really call one of its functions.

How do I use Getopt?

Syntax: getopt(int argc, char *const argv[], const char *optstring) optstring is simply a list of characters, each representing a single character option. Return Value: The getopt() function returns different values: If the option takes a value, that value is pointer to the external variable optarg.

What is Getopt long?

Getopt::Long is a module for parsing command line arguments (similar to Python's argparse). Using Getopt::Long, you can quickly define a standard Unix-like interface for your program. With just a few lines of code you can parse, type-check and assign the parameters passed to your program.

What is option in Perl?

In Perl, GetOptions() is defined as a function that is an extended function of Getopt::Long module which is mainly for parsing the command line using various options and this function uses functions that have long names instead of characters which are declared using a double dash (–).


1 Answers

Check out the section parsing options from an arbitrary string in the man page for Getopt::Long, I think it does exactly what you're looking for.

like image 75
Drew Stephens Avatar answered Sep 18 '22 18:09

Drew Stephens