in reply to Re: Getopts::Long -- changing its behavior
in thread Getopts::Long -- changing its behavior

Nope. What I want is to be able to do:

myscript.pl -file -name

And get the error that -file requires a string. In the case here, I don't get the error. I get file set to "-name". In other words, I want getopts to recognize that a switch has followed the one I wanted to take a string instead of a string as a required, so the user does not need to worry about what order s/he puts the switch in.


I admit it, I am Paco.
  • Comment on Re: Re: Getopts::Long -- changing its behavior

Replies are listed 'Best First'.
Re: Re: Re: Getopts::Long -- changing its behavior
by seattlejohn (Deacon) on Feb 06, 2002 at 07:14 UTC
    Something like this might do what you need:
    GetOptions(\%param, 'file:s', 'name:s', 'any:s', 'other:s', 'params:s' +); foreach (qw(file name any other params)) { die "Option $_ requires an argument\n" if defined($param{$_}) && $pa +ram{$_} eq ''; }

    Using the colon (e.g. 'file:s') in the GetOptions call instead of an equals sign makes a string parameter on the switch optional rather than required. As a result, when GetOptions sees '-file -name', it interprets this as 'switch -file with no optional string param, followed by switch -name with no optional string param', rather than as 'switch -file with string param -name'. Then the subsequent loop goes through and complains if one of those "optional" parameters in fact has an empty value.

    Also, if you check the perldoc for Getopt::Long you'll find that you can define handler subroutines to be called when an individual switch is encountered, which would probably also let you trap the case that's bothering you. I haven't used that capability in a while and it seems like it would be more work, but perhaps I haven't addressed all the angles of your question.

    Good luck!

      Thanks for the response, but again. Nope. Your answer is similiar to what I came up with, but what I was looking for is a configuration option that requires no extra written code. I just can't understand why getopts allows this. Kind of a pain.


      I admit it, I am Paco.