Search code examples
perlgetopt-long

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?


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.