How to parse a string with GetOpt :: Long :: GetOptions?

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

Develop:

I have a line

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

I want it to be parsed by GetOptions, so it's easier for me to add new parameters.

A workaround I would think is to split the string into spaces and replace @ARGV with a 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 a good / better way?

+7
perl getopt-long
source share
5 answers

Mark the section analysis parameters from an arbitrary line in man for Getopt :: Long , I think that it does exactly what you are looking for.

+15
source share

Instead of separating into spaces, use the built-in glob function. In addition to separating spaces, which will run standard command line extensions, return the list. (For example, * will give a list of files, etc.) I would also recommend localizing @ARG in a general way.

Also, this is the only way you can do this without overwriting GetOptions. (Clearly, I need to read the documentation more carefully.)

+7
source share

Wow !!!

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

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

The code might look something like this ...

 GetOptionsFromArray ([glob ($input_line)]); 

And this is only one line .. cool (I know I need to do some error checking, etc.) .. but that's cool ...

+5
source share

When you use Getopt :: Long for anything other than user input, keep in mind that some functions differ depending on the POSIXLY_CORRECT environment variable. You can override this with the appropriate call to Configure.

Mandatory POSIXLY_CORRECT joke .

0
source share

It seems that the GetOptionsFromArray and GetOptionsFromString methods were only added in version 3.26, and Murphy said that I only have version 2.35.

At the moment, I think I will have to live with a local @ARGV.

0
source share

All Articles