How do I parse a string with GetOpt::Long::GetOptions?
-
02-07-2019 - |
Question
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?
Solution
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.
OTHER TIPS
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.)
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 ...
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.
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.