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?
To use Getopt::Long from a Perl program, you must include the following line in your Perl program: use Getopt::Long; This will load the core of the Getopt::Long module and prepare your program for using it. Most of the actual Getopt::Long code is not loaded until you really call one of its functions.
Syntax: getopt(int argc, char *const argv[], const char *optstring) optstring is simply a list of characters, each representing a single character option. Return Value: The getopt() function returns different values: If the option takes a value, that value is pointer to the external variable optarg.
Getopt::Long is a module for parsing command line arguments (similar to Python's argparse). Using Getopt::Long, you can quickly define a standard Unix-like interface for your program. With just a few lines of code you can parse, type-check and assign the parameters passed to your program.
In Perl, GetOptions() is defined as a function that is an extended function of Getopt::Long module which is mainly for parsing the command line using various options and this function uses functions that have long names instead of characters which are declared using a double dash (–).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With