TTaJTa4
TTaJTa4

Reputation: 840

Insert and use unknown options in GetOptions

I'm trying to create a script (written in Perl) which gets arguments. The call should look as following:

./script [action] --option1 --option2 ... --optionK 

I use the GetOptions:Long module for that. Also I use the $ARG[0] in order to get the action. Example:

./script report --color black --version 19.4

Now I would like to give to the user the power to insert any command he wants (for example it can insert another script with arguments). I though of doing it like this: user can insert anything he wants at the end (only) of the command-line arguments, for example:

./script report --color black --version 19.4 more and more --info 551_5 from --the user

I would like to parse this array @ARGV and insert the additional information into a variable:

$additional = "more and more --info 551_5 from --the user"

I found out that after using the GetOptions, it will remove those options (not including $ARGV[0]) from the @ARGV array. Problem is, I really don't know how to get the additional information from the array. Maybe I should add an additional option, something like this:

./script report --color black --version 19.4 --additional more and more --info 551_5 from --the user

And get everything in additional. But in this way, I have another problem - it will treat --info and --the as arguments.

How can I solve this issue?

EDIT: I saw that pass_through is possible to use. But what if user has an option that similar to one of my available options? It could do some problems. Is it possible to handle it just like a string? Also in that way, I'll have to parse @ARGV and remove $ARGV[0] (the action).

EDIT-2: The -- method will work. But it feels to me as a workaround and not the proper way to solve this issue. There must be a cleaner way to do it. Maybe change to a different module?

Upvotes: 1

Views: 654

Answers (2)

JGNI
JGNI

Reputation: 4013

As @Ujin says -- will stop processing arguments at that point in the argument list. Another option that you almost got right is the use of --additional. This will work if you wrap the following text in quotes, ' for unix/linux and " for Windows. This will cause the shell to think that all the text after --additional, in the quotes, is one element to be passed into @ARGV. GetOptLong will then correctly see more and more --info 551_5 from --the user as the parameter for the --additional option. This makes your command line look like

./script report --color black --version 19.4 --additional 'more and more --info 551_5 from --the user'

Upvotes: 3

UjinT34
UjinT34

Reputation: 4987

You can use -- to separate additional arguments: ./script --option1 --option2 -- --userOption1 --userOption2

https://metacpan.org/pod/Getopt::Long#Mixing-command-line-option-with-other-arguments

Upvotes: 7

Related Questions