views:

788

answers:

5

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?

+7  A: 

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.)

+12  A: 

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.

Drew Stephens
+5  A: 

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 ...

Jagmal
The first argument is an array reference, so you want "GetOptionsFromArray([glob($input_line)],...)"
Michael Carman
Thanks Michael .. here goes the change in the code ...
Jagmal
A: 

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.

ysth
A: 

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.

Jagmal