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

5

7

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?

Titter answered 22/9, 2008 at 23:52 Comment(0)
L
16

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.

Lilywhite answered 23/9, 2008 at 0:15 Comment(0)
Q
7

Instead of splitting on whitespace, use the built-in glob function. In addition to splitting on whitespace, that will do the standard command line expansions, then return a list. (For instance * would give a list of files, etc.) I would also recommend local-izing @ARG on general principle.

Other than that, that's the only way you can do it without rewriting GetOptions. (Clearly I need to read the documentation more carefully.)

Quiz answered 23/9, 2008 at 0:5 Comment(0)
T
5

Wow!!!

I think I can use both of bentilly and dinomite's answers and do the following:

  • use glob to perform standard command line expansions
  • pass the array after glob to GetOptionsFromArray method of the GetOpt::Long (see here)

Code may look something like ...

GetOptionsFromArray ([glob ($input_line)]);

And that is only one line .. cool (I know I have to do some error checking etc) .. but its cool ...

Titter answered 23/9, 2008 at 0:23 Comment(1)
The first argument is an array reference, so you want "GetOptionsFromArray([glob($input_line)],...)"Thanasi
R
0

When you use Getopt::Long on something other than user input, be aware that some features are different based on the POSIXLY_CORRECT environment variable. You can override this with the appropriate call to Configure.

Obligatory POSIXLY_CORRECT anecdote.

Ronironica answered 23/9, 2008 at 7:22 Comment(0)
T
0

It seems like the methods GetOptionsFromArray and GetOptionsFromString were added only in v2.36 and as Murphy would say I have version 2.35 only.

For now, I think I will have to live with local @ARGV.

Titter answered 23/9, 2008 at 10:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.